我有一个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
答案 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
。