如何将查询结果存储在变量中

时间:2018-04-22 05:25:30

标签: sql sql-server stored-procedures

SQL Server存储过程:

CREATE PROCEDURE [dbo].[CheckTableStatus] 
    @DatabaseName AS NVARCHAR(50) = 'DBA',
    @ProjectID AS NVARCHAR(50) = 'CommandLog'
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @TableCount as int

    SET @Temp = 'DECLARE @cnt as int;'
    SET @Temp = @Temp + 'USE '+ @DatabaseName +'; SELECT @cnt=COUNT(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME=''' + @ProjectID + ''';'

    PRINT @Temp

    EXEC sp_executesql @temp

    --ASSIGN OUTPUT TO @TableCount
    IF @TableCount > 0  
       -- Do something
END

如何将正在执行的@temp的结果分配给变量@TableCount

3 个答案:

答案 0 :(得分:3)

如果您的目标是从@temp获取计数,请尝试在动态SQL中使用OUTPUT:

EXEC sp_executesql @temp, N'@cnt int OUTPUT', @TableCount OUTPUT

sp_executesql的这些新增内容会将动态SQL中的@cnt值输出到当前上下文中的@TableCount

答案 1 :(得分:1)

使用OUTPUT参数:

CREATE PROCEDURE [dbo].[CheckTableStatus] 
    @DatabaseName as nvarchar(50) = 'DBA',
    @ProjectID as nvarchar(50) = 'CommandLog'
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @TableCount as int,@Temp nvarchar(max)='';
--    SET @Temp = 'DECLARE @cnt as int;'
    SET @Temp = @Temp + 'USE '+ @DatabaseName +'; SELECT @cnt=COUNT(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME=''' + 
@ProjectID + ''';'
    print @Temp
    EXEC sp_executesql @temp,
      N'@cnt int out',@TableCount out;
    --ASSIGN OUTPUT TO @TableCount
    IF @TableCount >0 
     -- Do something
        print @TableCount;
END

但为什么不使用OBJECT_ID函数?

此外,您的代码也很容易SQL-injection

答案 2 :(得分:0)

您可以将值设置为

SET @TableCount = @cnt