现在我有一个存储过程,它接受2个表名(作为NVARCHAR
)并生成动态SQL来计算两个表的一些比较统计信息,然后使用EXEC sp_executesql
来执行动态SQL。
这一切都很有效。
但是我需要一种能够在EXEC dbo.stored_procedure_name
之后使用生成的表的方法。我知道这对于存储过程是不可能的,只有函数可以做到这一点。但是函数不能使用动态SQL。
那我怎么能做我需要的呢?我基本上需要某种东西,它需要一些参数,其中两个是表名,并输出一个可以在下游使用的表。
以下是我的存储过程的示例:
-- the stored procedure
CREATE PROCEDURE sp_myTest
@t1 NVARCHAR(MAX),
@t2 NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @row_count_t1 INT
DECLARE @row_count_t2 INT
DECLARE @row_count_difference INT
DECLARE @SQL NVARCHAR(MAX)
-- get # of rows in t1
SET @SQL = N'SELECT @row_count_out = COUNT(*) FROM ' + @t1
EXEC sp_executesql @SQL, N'@row_count_out INT OUTPUT', @row_count_out = @row_count_t1 OUTPUT;
-- get # of rows in t2
SET @SQL = N'SELECT @row_count_out = COUNT(*) FROM ' + @t2
EXEC sp_executesql @SQL, N'@row_count_out INT OUTPUT', @row_count_out = @row_count_t2 OUTPUT;
-- calculate difference
SET @row_count_difference = @row_count_t1 - @row_count_t2
-- print result
SET @SQL = N'SELECT @row_count_t1 AS "' + @t1 + '", @row_count_t2 AS "' + @t2 + '", @row_count_difference AS "Row_Count_Difference"'
EXEC sp_executesql @SQL, N'@row_count_t1 INT, @row_count_t2 INT, @row_count_difference INT', @row_count_t1 = @row_count_t1, @row_count_t2 = @row_count_t2, @row_count_difference = @row_count_difference
END
GO
-- usage
EXEC sp_myTest 'table1', 'table2'
答案 0 :(得分:0)
但我需要一种能够在EXEC dbo.stored_procedure_name
之后使用生成的表的方法
据我所知,您可以将数据保存到临时表(或实际表)中 如下: -
而不是最后两行: -
SET @SQL = N'SELECT @row_count_t1 AS "' + @t1 + '", @row_count_t2 AS "' + @t2 + '", @row_count_difference AS "Row_Count_Difference"'
EXEC sp_executesql @SQL, N'@row_count_t1 INT, @row_count_t2 INT, @row_count_difference INT', @row_count_t1 = @row_count_t1, @row_count_t2 = @row_count_t2, @row_count_difference = @row_count_difference
键入下一行: -
if exists (select 1 from sys.tables where name = 'TblResult')
begin
Drop table TblResult
print 'TblResult table has been dropped'
end
-- print result
SET @SQL = N'SELECT @row_count_t1 AS "' + @t1 + '", @row_count_t2 AS "' + @t2 + '", @row_count_difference AS "Row_Count_Difference" into TblResult'
EXEC sp_executesql @SQL, N'@row_count_t1 INT, @row_count_t2 INT, @row_count_difference INT', @row_count_t1 = @row_count_t1, @row_count_t2 = @row_count_t2, @row_count_difference = @row_count_difference
select * from TblResult
修复是: -
使用INTO
子句将数据保存到TblResult
表中。
要将程序设置为可使用一次而不会出现任何错误,请检查statmnet是否已删除TblResult(如果存在)。
您可以通过在表名开头添加#
来使用临时表而不是真实表
现在您的结果将保存到TblResult表中,并根据需要使用它。
答案 1 :(得分:0)
CREATE PROCEDURE sp_myTest
@t1 NVARCHAR(MAX),
@t2 NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = N'SELECT
(SELECT COUNT(*) FROM ' + @t1+') AS '+@t1+',
(SELECT COUNT(*) FROM ' + @t2+') AS '+@t1+',
((SELECT COUNT(*) FROM ' + @t1+') - (SELECT COUNT(*) FROM ' + @t2+')) AS row_count_difference;'
EXEC sp_executesql @SQL;
END;