表:
create table TabA
(ID int, Name varchar(20))
insert into TabA
select 1,'ABC' union
select 2,'DEF' union
select 3,'GHD'
create table TabB
(ID int, Name varchar(20))
insert into TabA
select 1,'XYZ' union
select 2,'STF' union
select 3,'LDZ'
create table status
(Result1 int,Result2 int )
Create table query(query1 varchar(1000),query2 varchar(1000))
Insert into query(query1,query2)
select '''select COUNT(*) from TabA''','''select COUNT(* )from TabB'''
select * from query
程序:
create Procedure [dbo].spStatus
AS
BEGIN
SET NOCOUNT ON;
Declare @sqlString1 nvarchar(1000)
,@sqlString2 nvarchar(1000)
,@col_value1 varchar(256)
,@col_value2 varchar(256)
select @sqlString1 = query1
, @sqlString2 =query2
from Query
EXEC sp_executesql
@query=@sqlString1, --sql string is your full select statement
@params = N'@col_Value1 varchar(256) OUTPUT',
@col_Value1 = @col_Value1 OUTPUT
print(@sqlString1)
-- @sqlString2, --sql string is your full select statement
--@params = N'@col_Value2 varchar(256) OUTPUT',
-- @col_Value2 = @col_Value2 OUTPUT
Insert Into dbo.Status(Result1,Result2 )
Values(@col_Value1,@col_Value2)
End
如果我们仅使用@query=@sqlString1
,但我希望两个语句@query=@sqlString1,@query=@sqlString2
应该一起执行,它就有效。
请帮助我们如何使用这两个语句执行?
先谢谢
答案 0 :(得分:3)
你的意思是:
SET @sqlString1 = @sqlString1 + ';' + @sqlString2;
EXEC sp_executesql @query = @sqlString1 --...
答案 1 :(得分:1)
将两个查询与+(@query=@sqlString1 + '; ' + @sqlString2)
然后使用两个变量将两个计数捕获到输出变量
OR
Insert into query(query1,query2)
EXEC sp_executesql 'SELECT ( select COUNT(*) from TabA ) AS query1, ( select COUNT(*)from TabB ) AS query2'
...但根本不需要真正的动态SQL。
答案 2 :(得分:0)
试试这个:
--add this
DECLARE @SQL nvarchar(max)
SET @SQL=ISNULL(@sqlString1,'')+';'+ISNULL(@sqlString2,'')
--change this
EXEC sp_executesql @query=@SQL
,@params = N'@col_Value1 varchar(256) OUTPUT'
,@col_Value1 = @col_Value1 OUTPUT