动态SQL显示成功但不更新行

时间:2015-03-05 21:14:44

标签: sql-server stored-procedures sql-server-2008-r2 dynamicquery

我是SQL Server和存储过程的新手,据说我正在使用SQL Server 2008 R2尝试创建一个动态查询,允许我传入表名和一些参数来更新某些行。

存储过程运行并说成功完成但行永远不会更新。如果我分解查询并单独运行它们,它们一起工作,但没有任何东西。

我尝试使用print和select语句来显示我的查询和进度,但没有打印出来。

ALTER PROCEDURE [dbo].[sp_testing_drew]
    -- Add the parameters for the stored procedure here
    @Table_Name sysname,
    @id int,
    @username varchar(25)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    DECLARE @recipeName varchar(25),
        @idApp varchar(10),
        @DynamicSQL1 nvarchar(4000),
        @DynamicSQL2 nvarchar(4000),
        @DynamicSQL3 nvarchar(4000),
        @DynamicSQL4 nvarchar(4000)

    -- Set the recipe name, finding it first by its ID  
    --SELECT @recipeName = Recipe_Name FROM LC2Recipes WHERE LC2RecipesID = 551;
    SET @DynamicSQL1 = N'SELECT '+@recipeName+' = Recipe_Name FROM '+@Table_Name+' WHERE LC2RecipesID = '+CAST(@id AS varchar(10))+';'
    EXECUTE sp_executesql @DynamicSQL1

    -- Get the ID of the approved recipe
    --SET @DynamicSQL2 = N'SELECT TOP 1 ' + @idApp + ' = ' + @Table_Name + 'ID FROM ' + @Table_Name + ' WHERE Recipe_Name = ''' + @recipeName + ''' ORDER BY Major_Revision DESC;'
    SET @DynamicSQL2 = N'SELECT TOP 1 '+@idApp+' = LC2RecipesID FROM '+@Table_Name+' WHERE Recipe_Name = '''+@recipeName+''' ORDER BY Major_Revision DESC;'
    EXECUTE sp_executesql @DynamicSQL2

    -- 4 is Archived, 1 is approved, set the user who approved
    --SET @DynamicSQL3 = N'UPDATE ' + @Table_Name + ' SET Status = 4 WHERE Recipe_Name = ''' + @recipeName + '';
    SET @DynamicSQL3 = N'UPDATE '+@Table_Name+' SET Status = 4 WHERE Recipe_Name = '''+@recipeName+''';'
    EXECUTE sp_executesql @DynamicSQL3

    --SET @DynamicSQL4 = N'UPDATE ' + @Table_Name + ' SET Approved_By = ''' + @username + ''', Status = 1 WHERE ' + @Table_Name + 'ID = ' + CAST(@idApp AS varchar(10));
    SET @DynamicSQL4 = N'UPDATE '+@Table_Name+' SET Approved_By = '''+@username+''', Status = 1 WHERE '+@Table_Name+'ID = '+@idApp+';'
    EXECUTE sp_executesql @DynamicSQL4
END

1 个答案:

答案 0 :(得分:0)

您需要设置变量@recipeName&的值。 @idApp。这导致了问题,只需设置这些变量的值,你应该没问题,