在Variable中恢复动态查询结果

时间:2013-04-17 05:55:31

标签: sql tsql sql-server-2008-r2

我有一个SP会返回下一个代码。我将传递TableName,IdentityColumnName,CodeColumn和ConditionColumn。很简单,我想将动态查询结果保存在变量中,此查询将向我返回单个值。此SP将适用于3个表。问题是我的动态查询未设置为@query变量,任何帮助。

  ALTER PROC [dbo].[usp_GetNextCode]
    (
        @IdColumnName nvarchar(20)= 'HeadId',                
        @CodeColumnName nvarchar(100)= 'HeadCode',           
        @TableName nvarchar(50)= 'Head',                     
        @MaxColumnName varchar(50) = 'FamilyId',             
        @MaxColumnValue varchar(3) = 1                       
    )
    AS
    BEGIN
        DECLARE @query varchar(max) , @NewId VARCHAR(30),@LastCode varchar(30)
        ---First Get the Last Inserted Code and save it in a Variable..
        SET @query =    'Select      '+ @LastCode +'='+ @CodeColumnName +'
                        FROM         Account.' + @TableName 
                     + ' Where '    + @IdColumnName + ' = (
                                    SELECT      MAX(' + @IdColumnName + '  ) 
                                    FROM        Account.' + @TableName +'  
                                    where       '+ @MaxColumnName  + ' = ' + @MaxColumnValue  +' )'
        Select @query
        EXEC(@query)
        Select @LastCode
    END

1 个答案:

答案 0 :(得分:1)

您需要使用sp_executesql,因为您需要/需要为动态查询使用输出参数:

ALTER PROC [dbo].[usp_GetNextCode]
(
    @IdColumnName nvarchar(20)= 'HeadId',                
    @CodeColumnName nvarchar(100)= 'HeadCode',           
    @TableName nvarchar(50)= 'Head',                     
    @MaxColumnName varchar(50) = 'FamilyId',             
    @MaxColumnValue varchar(3) = 1
)
AS
BEGIN

        DECLARE @query nvarchar(max) , @NewId VARCHAR(30),@LastCode varchar(30)
        DECLARE @parms nvarchar(max)
        ---First Get the Last Inserted Code and save it in a Variable..
        SET @query =    'Select      @LastCode='+ @CodeColumnName +'
                        FROM         Account.' + @TableName 
                     + ' Where '    + @IdColumnName + ' = (
                                    SELECT      MAX(' + @IdColumnName + '  ) 
                                    FROM        Account.' + @TableName +'  
                                    where       '+ @MaxColumnName  + ' = ' + @MaxColumnValue  +' )'
        SET @parms = '@LastCode varchar(30) output'
        Select @query
        EXEC sp_executesql @query,@parms,@LastCode output
        Select @LastCode
END

目前,您正在将@LastCode连接到@query字符串中 - 因为它是NULL,您的整个@query } string变为NULL