通过将表名称,ColumnName作为变量使用游标来更新表

时间:2011-09-21 07:22:42

标签: sql sql-server-2008 sql-server-2005 variables sql-update

我想更新表格。我从前端获取表名和列名作为XML数据集。我为此写了一个光标。但它会引发错误。下面是我的Cursor

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PMT_Formstatus_Update_Test]
(
@XMLTableNames VARCHAR(MAX)
)
AS
BEGIN

DECLARE @docHandle INT, @ErrorMessage VARCHAR(200), @doc VARCHAR(200)
    SET @doc = '<?xml version="1.0" encoding="iso-8859-1" ?>'

    DECLARE @Names TABLE
(   
        TName VARCHAR(50),
    CName VARCHAR(50),
    IDField VARCHAR(50),
    FunctionID INT,
    ID INT,             
    StatusID INT
    )
    SET @XMLTableNames = @doc + @XMLTableNames          
EXEC sp_xml_preparedocument @docHandle OUTPUT,  @XMLTableNames
    INSERT INTO @Names
    SELECT * FROM 
        OPENXML(@docHandle,'NewDataSet/NameDetails',2)
            WITH
            (
                TName VARCHAR(50),
                CName VARCHAR(50),
                IDField VARCHAR(50),
                FunctionID INT,
                ID INT,
                StatusID INT
                            )

    DECLARE @FunctionID INT
DECLARE @StatusID INT
DECLARE @ID INT
    DECLARE @TableName VARCHAR(50)
    DECLARE @ColumnName VARCHAR(50)
DECLARE @IDField VARCHAR(50)

    DECLARE @getTables CURSOR
    SET @getTables = CURSOR FOR
    SELECT FunctionID, TName, CName, StatusID, IDField, ID FROM @Names
    OPEN @getTables
    FETCH NEXT
    FROM @getTables INTO @FunctionID, @TableName, @ColumnName, @StatusID, @IDField, @ID
    WHILE @@FETCH_STATUS = 0
    BEGIN
    UPDATE @TableName SET @ColumnName = 3 WHERE @IDField = @ID
        FETCH NEXT
    FROM @getTables INTO @FunctionID, @TableName, @ColumnName, @StatusID, @IDField, @ID
    END

    CLOSE @getTables
    DEALLOCATE @getTables
END

在这种情况下如何编写更新查询?我需要你的所有建议......

3 个答案:

答案 0 :(得分:1)

简单动态SQL示例:

DECLARE @SQL NVARCHAR(max),@TableName VARCHAR(128),@ColumnName1 VARCHAR(128),@ColumnName2 VARCHAR(128),@Value NVARCHAR(MAX),@NewValue NVARCHAR(MAX)
SET @TableName='User'
SET @ColumnName1='Session_Id'
SET @ColumnName2='Session_Id_Old'
SET @Value=''''+CAST(NEWID() as NVARCHAR(50))+''''
SET @NewValue=''''+CAST(NEWID() as NVARCHAR(50))+''''

SET @SQL=
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
'UPDATE [@TableName] SET [@ColumnName1] = @NewValue WHERE [@ColumnName2]= @Value','@TableName',@TableName),
'@ColumnName1',@ColumnName1),'@Value',@Value),'@NewValue',@NewValue),'@ColumnName2',@ColumnName2)
        EXECUTE(@SQL)

如果数据类型是字符串

,则应将撇号添加到旧值/新值的两侧

答案 1 :(得分:1)

你可以希望看到为什么你写的东西不起作用,因为它是一个针对表变量执行的更新语句,它不影响该表中的实际列:

declare @TableName table (ID int not null)
declare @ColumnName1 int
declare @ColumnName2 int
declare @Value int
UPDATE @TableName SET @ColumnName1 = 3 WHERE @ColumnName2= @Value

尝试实现您正在做的事情的一种方法是动态SQL。这很难看(如果列中的数据类型不同,情况会更糟)。 T-SQL中没有真正的“元编程”系统。

答案 2 :(得分:1)

您需要将它们连接为字符串,然后调用EXEC('')

EXEC ('UPDATE TableName SET ColumnName1 = 3 WHERE ColumnName2= Value')