如何使用表名,标识和列名更新SQL Server列

时间:2016-06-09 12:27:46

标签: sql-server

当我输入表名,记录ID和字段名时,我有一个读取列值的过程:

 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO

 ALTER PROCEDURE [dbo].[GET_TEXT_DETAIL]
    @id uniqueidentifier,
    @table varchar(255),
    @field varchar(max)
 AS
 BEGIN
     SET NOCOUNT ON;

     DECLARE @sql VARCHAR(200)

     SET @sql = 'select ' + QUOTENAME(@field) + ' from ' + QUOTENAME(@table) + ' where ID = ''' + cast(@id as varchar(36)) + ''''

     EXEC(@sql)
 END

现在我尝试使用相同的方法更新该列:

 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO

 ALTER PROCEDURE [dbo].[UPDATE_TEXT_DETAIL]
     @id uniqueidentifier,
     @table varchar(255),
     @field varchar(max),
     @fieldvalue varchar(max)
 AS
 BEGIN
     SET NOCOUNT ON;

     DECLARE @sql varchar(200)

     SET @sql = 'update ' + QUOTENAME(@table) + ' set ' + QUOTENAME(@field) + ' = ''' + QUOTENAME(@fieldvalue) + ''' where ID = ''' + cast(@id as varchar(36)) + ''''

     EXEC(@sql)
 END

但是我会根据自己的行为得到多个错误。记录ID是唯一标识符。此外,列值有时会随其周围的[]字符更新。我知道这是QUOTENAME的默认值,但我想解决这个问题。当我使用单引号时,我会收到有关ID的错误。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

试试这个 - >

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[UPDATE_TEXT_DETAIL]
@id         uniqueidentifier,
@table      varchar(255),
@field      varchar(max),
@fieldvalue varchar(max)
AS

BEGIN

    SET NOCOUNT ON;

    declare @sql varchar(200)
    --set @sql = 'select ' + QUOTENAME(@field) + ' from ' + QUOTENAME(@table) + ' where ID = ''' + cast(@id as varchar(36)) + ''''
    set @sql = 'update ' + QUOTENAME(@table) + ' set ' + QUOTENAME(@field) + ' = ' + QUOTENAME(@fieldvalue, '''') + ' where ID = ''' + cast(@id as varchar(36)) + ''''
    EXEC(@sql)


END