SQL Server存储过程错误:声明表变量必需

时间:2015-02-19 19:12:02

标签: sql-server stored-procedures

但是虽然我的眼睛似乎一切正常,但在尝试执行时出错:

  

声明表变量" @_ Tbl"

代码:

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE dbo.sp_setSettings
(
    @UID nvarchar(50),
    @Tbl nvarchar(30),
    @Fld nvarchar(30),
    @Vle nvarchar (200),
    @WFld nvarchar (30),
    @WVle nvarchar (200)
)
AS
    SET NOCOUNT ON;
    DECLARE @S nvarchar(max)='',
            @P nvarchar(max)='',
            @W nvarchar(max)=''

    IF @Tbl <> 'Users' 
       SET @W = ' AND @_WFld=@_WVle'

    SET @S = 'UPDATE @_Tbl SET @_Fld = @_Vle WHERE UID=@_UID' + @W

    --print @S
    SET @P = '@_UID nvarchar(50),
              @_Tbl nvarchar(30),
              @_Fld nvarchar(30),
              @_Vle nvarchar(200),
              @_WFld nvarchar(30),
              @_WVle nvarchar(200)'

    EXEC sp_executesql @S,@P,@UID,@Tbl,@Fld,@Vle,@WFld,@WVle

    SET NOCOUNT OFF

有人可以提出错误吗?

2 个答案:

答案 0 :(得分:1)

使用所有修复和sql-injection免费

CREATE PROCEDURE dbo.sp_setSettings
(
    @UID    nvarchar(50),
    @Tbl    SYSNAME,
    @Fld    SYSNAME,
    @Vle    nvarchar(200),
    @WFld   SYSNAME,
    @WVle   nvarchar (200)
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @S nvarchar(max), @P nvarchar(max);

 SET @S = N' UPDATE ' + QUOTENAME(@Tbl) 
        + N'  SET ' + QUOTENAME(@Fld) + N'  = @_Vle  '
        + N' WHERE UID = @_UID  '
        + CASE WHEN (@Tbl <> 'Users') 
          THEN N' AND ' + QUOTENAME(@WFld) + N' = @_WVle' 
           ELSE N' ' END

    --print @S
    SET @P = N'@_UID nvarchar(50),
               @_Vle nvarchar(200),
               @_WVle nvarchar(200)'

    EXEC sp_executesql @S
                      ,@P
                      ,@_UID = @UID
                      ,@_Vle = @Vle
                      ,@_WVle = @WVle

    SET NOCOUNT OFF;
END

答案 1 :(得分:0)

您不能在更新的表名部分中使用变量 我会做类似

的事情
SELECT @OBJ_ID = OBJECT_ID
FROM SYS.tables
 WHERE name =  @Tbl 

验证表是否存在 然后将其插入@s之类的

 SET @S = 'UPDATE '+@Tbl+' SET @_Fld = @_Vle WHERE UID=@_UID' + @W