我想创建一个查询,该查询返回查询中某些选择语句参数的总和,并创建一个具有新行的新结果表,该行是从以下选择语句派生的结果。
这是我的桌子。
我希望结果如下所示,其中Col4是具有第2、3和5行的select语句的结果,而第5列是对col值的计算结果,如下所示
--http://sqlfiddle.com/#!18/87a6f/4
--Schema
create table mytable(col1 int,col2 int,col3 int,col4 int)
insert into mytable values
(111,1,0,4),
(112,3,1,2),
(113,1,2,2),
(114,2,4,3),
(115,3,1,0),
(116,1,0,2),
(117,2,1,0),
(118,4,1,3),
(119,3,2,1)
create table tabscript (col4 varchar(max),col5 varchar(max))
create table tabresult(col4 varchar(max),col5 int)
insert into tabscript(col4,col5) values('112,113,115','sum(col2+col3+col4)'),
('115,117,119','sum(col2+col3+col4)'),('114,118,111','sum(col2+col3+col4)')
--Kamel Gazzah
[email protected]
--29/10/2019
declare @script as varchar(max)
declare @sqlCommand as nvarchar(max)
declare @result as int
declare mycursor cursor for
select concat('select @result=',col5, ' from mytable where col1 in(',col4,')')
from tabscript
open mycursor
declare @sql as nvarchar(max)
fetch mycursor into @sqlCommand
while @@fetch_status=0
begin
--print @sql
--print @sqlCommand
exec sp_executesql @sqlCommand,N'@result int output',@result output
insert into tabresult values(@sqlcommand,@result)
fetch mycursor into @sqlCommand
end
close mycursor
deallocate mycursor
go
select * from tabresult