SQLSERVER 我有一个表,查出来的一个字段是字符串表达式
比如
a b c 5*6-3
a be ce 15*(6-3)
a b c 36-3
a be ce 1*(9-8)
我想在此后面增加一列字段,把计算结果输出来,
a b c 5*6-3 27
a be ce 15*(6-3) 45
a b c 36-3 33
a be ce 1*(9-8) 1
如何用SQL或者存储过程实现呢?有没有比较简单的方法实现呢?谢谢
SQL code:
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([col1] varchar(1),[col2] varchar(2),[col3] varchar(2),[col4] varchar(8))
insert [tb]
select 'a','b','c','5*6-3' union all
select 'a','be','ce','15*(6-3)' union all
select 'a','b','c','36-3' union all
select 'a','be','ce','1*(9-8)'
declare @sql varchar(8000)
select
@sql=isnull(@sql+' union all ','')
+'select '''+col1+''' as col1,'''+col2+''' as col2,'''+col3+''' as col3,'''+col4+''' as col4,'+col4+' as col5 '
from tb
exec (@sql)
/**
col1 col2 col3 col4 col5
---- ---- ---- -------- -----------
a b c 5*6-3 27
a be ce 15*(6-3) 45
a b c 36-3 33
a be ce 1*(9-8) 1
(4 行受影响)
**/
SQL code
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.Code