[英]Merge inserted values against temp table leaving out null values
In my process I need to create an INSTEAD OF INSERT
trigger which will accept the new values for the record and create a new version of it, example: 在我的过程中,我需要创建一个
INSTEAD OF INSERT
触发器,该触发器将接受记录的新值并为其创建新版本,例如:
Note: Table columns are constantly changing due to business requirements. 注意:由于业务需求,表列会不断变化。 So if there is a solution that would support
table to table
merge instead of column to column
that would be awesome. 因此,如果有一种解决方案将支持
table to table
合并而不是column to column
合并,那就太棒了。
ExampleTable ExampleTable
VersionID |ID |Value 1 |Value 2
1 |1 |abc | 123
Example query 查询示例
INSERT INTO ExampleTable (ID,[Value 1]) VALUES (1,'testabc')
Resulting table: 结果表:
VersionID |ID |Value 1 |Value 2
1 |1 |abc | 123
2 |1 |testabc | 123
At this moment I have something like this: 在这一刻,我有这样的事情:
-- Get data
SELECT TOP 1 * INTO #ExistingData FROM dbo.ExampleTableLatestVersionView
WHERE ID = @ID
-- Merge incoming data
MERGE #ExistingData AS target
USING inserted as source
ON (target.ID= source.ID)
WHEN MATCHED
THEN UPDATE SET target.[Value 1] = source.[Value 1],
target.[Value 2] = source.[Value 2];
-- And afterwards I do a new insert into version table
Problem here is that NULL
values from inserted
table are overwriting and I end up with this: 这里的问题是
inserted
表中的NULL
值inserted
被覆盖,而我最终得到以下结果:
VersionID |ID |Value 1 |Value 2
1 |1 |abc | 123
2 |1 |testabc | NULL
I was thinking of doing INSTEAD OF UPDATE
where I could get previous values by referencing VersionID
, but I want to know if this is possible. 我当时正在考虑进行
INSTEAD OF UPDATE
,通过引用VersionID
可以获取以前的值,但是我想知道是否可行。
This will use the existing value if provided value is null: 如果提供的值为null,则将使用现有值:
MERGE #ExistingData AS target
USING inserted as source
ON (target.ID= source.ID)
WHEN MATCHED
THEN UPDATE SET target.[Value 1] = ISNULL( source.[Value 1],target.[Value 1]),
target.[Value 2] = ISNULL( source.[Value 2],target.[Value 2]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.