在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"在专栏的某个地方。
当我不知道源表中列的正确位置时,如何将目标列设置为正确的列?我对正确列的唯一了解就是它包含一个特定的字符串......
答案 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;