我试图在存储过程中获取生成的sql的值.
执行此操作
DECLARE @sSQL varchar(5000), @retval int DECLARE @tablename varchar(50) SELECT @tablename = 'products' SELECT @sSQL = 'SELECT @retval = MAX(ID)' SELECT @sSQL = @sSQL + ' FROM ' + @tablename EXEC (@sSQL) SELECT @retval
我明白了
Must declare the variable '@retval'.
如何在不使用游标的情况下获取值(我正试图避免)?
您将需要使用sp_executesql:
DECLARE @retval int DECLARE @sSQL nvarchar(500); DECLARE @ParmDefinition nvarchar(500); DECLARE @tablename nvarchar(50) SELECT @tablename = N'products' SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename; SET @ParmDefinition = N'@retvalOUT int OUTPUT'; EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT; SELECT @retval;