0

任何人都知道为表生成通用 UPDATE 语句的方法。我想传递一个表名作为参数,结果应该是一个 UPDATE 语句,如:

UPDATE [LinkedServer].[dbo].mytable foreign
SET Col2 = local.Col2, 
    Col3 = local.Col3
FROM mytable local
WHERE foreign.Col1 =  local.Col1
4

1 回答 1

0

这现在有效:

注意:我的主键是作为唯一约束创建的,名称为“PrimaryKey”。

/*------------------------------------------------*/
/*        Create generic UPDATE statement         */
/*------------------------------------------------*/
IF EXISTS (SELECT name FROM sysobjects 
           WHERE name = 'GetUpdateStatement' AND type = 'FN')
   DROP FUNCTION dbo.GetUpdateStatement
GO

CREATE FUNCTION dbo.GetUpdateStatement
    (@TableName varchar(40),
     @LinkedServer varchar(100))    
    RETURNS varChar(max)
    --WITH ENCRYPTION
     AS 
BEGIN

DECLARE @sql varchar(max) = ''
DECLARE @where varchar(max) = ''

SET @sql = 'UPDATE [' + @LinkedServer + '].[dbo].[' + @TableName + '] ' +
           'SET '
--Add all the columns
DECLARE C CURSOR FOR
SELECT Column_Name
FROM information_schema.columns 
WHERE TABLE_NAME = @TableName
  AND Column_Name <> 'Systimestamp'
ORDER BY ordinal_position
OPEN C

DECLARE @colname varchar(40)
DECLARE @isPK smallint
FETCH NEXT FROM C INTO @colname

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @isPK = (SELECT 1
                 FROM sys.indexes MyIndex
                 INNER JOIN sys.index_columns IndexColumns 
                    ON  MyIndex.index_id = IndexColumns.index_id
                    AND MyIndex.object_id = IndexColumns.object_id 
                 INNER JOIN sys.columns Columns
                    ON  Columns.column_id = IndexColumns.column_id 
                    AND IndexColumns.object_id = Columns.object_id 
                 INNER JOIN sys.objects Objects ON Objects.object_id = Columns.object_id 
                 WHERE Columns.name = @colname
                   AND Objects.name = @TableName
                   AND MyIndex.Name='PrimaryKey')
    IF @isPK = 1
        SET @where = @where + '[' + @LinkedServer + '].[dbo].[' + @TableName + '].' + @colname + ' = Source.' + @colname + ' AND '
    ELSE
        SET @sql = @sql + @colname + ' = Source.' + @colname + ', '

    FETCH NEXT FROM C INTO @colname
END
CLOSE C
DEALLOCATE C
--Remove the last comma
SET @sql = LEFT(@sql, LEN(@sql) - 1) + ' '
SET @where = LEFT(@where, LEN(@where) - 4) 

--Add FROM
SET @sql = @sql + 'FROM ' + @TableName + ' AS Source '

--Add WHERE of the PK's
SET @sql = @sql + 'WHERE ' + @where

RETURN @sql

END
于 2013-05-31T13:29:34.893 回答