SQL Server:如何使用动态列进行合并?

时间:2017-11-10 15:19:53

标签: tsql sql-server-2016

在SQL Server 2016中,我有一个如下所示的合并语句:

MERGE dbo.MyTable AS TARGET 
USING (SELECT * FROM dbo.StageTable)

WHEN MATCHED 
   THEN 
      UPDATE SET target.[StartTime] = source.[UnknownColumn]

我的source表包含随机生成的顺序列。换句话说," StartTime" target表中的列可以等于Column1或Column2或Column3等,但它总是包含单词" StartTime"在专栏的某个地方。

当我不知道源表中列的正确位置时,如何将目标列设置为正确的列?我对正确列的唯一了解就是它包含一个特定的字符串......

1 个答案:

答案 0 :(得分:0)

您需要使用动态T-SQL语句。像这样:

DECLARE @DynamicTSQLStatement NVARCHAR(MAX)
       ,@ColumnName SYSNAME;

SELECT @ColumnName = [name]
FROM [sys].[columns]
WHERE [object_id] = OBJECT_ID('[dbo].[StackOverflow]')
    AND [name] LIKE '%StartTime%';


SET @DynamicTSQLStatement = N'MERGE dbo.MyTable AS TARGET 
USING (SELECT * FROM dbo.StageTable)

WHEN MATCHED 
   THEN 
      UPDATE SET target.[StartTime] = source.[' + @ColumnName + '];';

EXEC sp_executesql @DynamicTSQLStatement;