我有一个包含150多列的Source
和Target
表,实际上问题是我需要比较,并在我的MERGE
语句中插入此150列,是否存在还有其他办法吗?
MERGE targettable AS [Target]
USING (
---Source Query*
) AS [Source] ON [Target].Key = [Source].Key
WHEN MATCHED --Matching records with change //Update
AND [Target].[StartDt] <> [Source].[StartDt]
OR [Target].[ADStatusDesc] <> [Source].[ADStatusDesc]
..... --more than 150 columns
OR [Target].[StatusInd] <> [Source].[StatusInd]
THEN
UPDATE
SET [Target].[StartDt] = [Source].[StartDt]
.... ----more than 150 columns
,[Target].[StatusInd]= [Source].[StatusInd]
答案 0 :(得分:1)
是的,您需要明确拼写出来。但您可以生成该代码:
SELECT
col.name
, N' OR NOT(a.' + QUOTENAME(col.name) + N' = b.' + QUOTENAME(col.name) + N' OR (a.' + QUOTENAME(col.name) + N' IS NULL AND b.' + QUOTENAME(col.name) + N' IS NULL))'
FROM sys.columns col
JOIN sys.objects obj ON col.object_id = obj.object_id
JOIN sys.types tp ON col.user_type_id = tp.user_type_id
WHERE obj.name = 'TableNameHere' AND col.is_computed = 0
ORDER BY col.column_id
这也适当地处理NULL
值。对于字符串,您应该添加collation子句以使用二进制排序规则。
答案 1 :(得分:0)
[Target].Key = [Source].Key
时使用[Source]数据简单地更新[Target]的所有列,因为[Source]包含好/新值?