存储过程中的Select&Update语句

时间:2018-07-04 06:39:27

标签: sql-server

我试图首先使用select语句编写存储过程,如果该语句有效,则运行update语句。下面的示例代码,其中table1有两列TableNameColumnName。如果有table1返回的记录,请运行update语句,其中的表名和列取自table1结果:

DECLARE @tablename NVARCHAR(100), 
        @columnname NVARCHAR(100), 
        @newid INT, 
        @sql NVARCHAR(500), 
        @Id INT,  
        @name NVARCHAR(50), 
        @result NVARCHAR(100)

SET @newid = 0
SET @Id = 1
SET @name = 'aa'
SET @result = 'test'

SELECT 
    @newid = Id, @tablename = TableName, @columnname = ColumnName 
FROM
    Table1 
WHERE
    Id = @Id

IF(@newid > 0)
BEGIN
    SET @sql = 'UPDATE ' + @tablename + ' SET ' + @columnname + ' = ' + @result + 'where name = ' +@name
END

但是,该脚本无法正常工作。有人可以帮忙吗?谢谢

3 个答案:

答案 0 :(得分:0)

您执行查询。

使用 EXEC 尝试使用此代码。

Create  PROCEDURE [dbo].[procedure_name]
 @tablename NVARCHAR(100), 
        @columnname NVARCHAR(100), 
        @newid INT, 
        @sql NVARCHAR(500), 
        @Id INT,  
        @name NVARCHAR(50), 
        @result NVARCHAR(100)

AS

SET NOCOUNT ON



SET @newid = 0
SET @Id = 1
SET @name = 'aa'
SET @result = 'test'

SELECT 
    @newid = 1, @tablename = 'abc', @columnname = 'b' 

WHERE
    1 = @Id

IF(@newid > 0)
BEGIN
      SET @sql = 'UPDATE ' + @tablename + ' SET ' + @columnname + ' = ''' + @result + ''' where name = ''' +@name+''''

    PRINT @sql
   EXEC @sql
END

答案 1 :(得分:0)

在硬编码文字中添加单引号。

set @sql = 'UPDATE ' + @tablename + ' SET ' + @columnname + ' = ''' + @result + ''' where name = ''' +@name + ''''

在执行动态SQL检查错误之前,请记住打印动态SQL。

PRINT (@sql)

答案 2 :(得分:0)

您的查询应如下所示

DECLARE @tablename NVARCHAR(100), 
        @columnname NVARCHAR(100), 
        @newid INT, 
        @sql NVARCHAR(500), 
        @Id INT,  
        @name NVARCHAR(50), 
        @result NVARCHAR(100)

SET @newid = 0
SET @Id = 1
SET @name = 'aa'
SET @result = 'test'

SELECT 
    @newid = Id, @tablename = TableName, @columnname = ColumnName 
FROM
    Table1 
WHERE
    Id = @Id

IF(@newid > 0)
BEGIN
    SET @sql = 'UPDATE ' + @tablename + ' SET ' + @columnname + ' = ' + @result + 'where name = ' +@name
    exec sp_executesql @sql
END