SQL合并与可变的值数
我想知道是否可以以某种方式编写合并语句来支持不同的列计数的值集?
首先,如果我们有一个定义如下的表:
CREATE TABLE [Example]
(
[Id] NVARCHAR(10) NOT NULL,
[Name] NVARCHAR(100) NOT NULL,
[Format] NVARCHAR(MAX) DEFAULT('yyyy-MM-dd')
)
是否可以在某种程度上创建一个单个合并语句,该语句支持有或没有格式列的条目? 可以调整以下工作吗?
MERGE [Example] AS t
USING
(
VALUES
('id1', 'England', 'dd/MM/yyyy'),
('id2', 'Germany'), -- The expectation is that the default value would be used
('id3', 'America', 'MM.dd.yyyy')
) AS s([Id], [Name], [Format])
ON
s.[Id] = t.[Id]
WHEN MATCHED THEN
UPDATE SET
t.[Name] = s.[Name],
t.[Format] = s.[Format]
WHEN NOT MATCHED THEN
INSERT ([Id], [Name], [Format])
VALUES (s.[Id], s.[Name], s.[Format]);
这是不起作用的,因为德国条目只有2个值,这与定义的列数不匹配。我已经尝试添加('id2','dermany',null)
,但这插入了null
,而不是为列定义的默认值。我还尝试过添加('id2','dermany',默认值)
,但由于语法错误而失败。
我会尽可能吗?到目前为止,我唯一的解决方案是维护两个Separte Merge语句,一个带有格式列,一个没有 - 是否有任何方法可以将它们整合在一起?
I would like to know if a MERGE statement could, somehow, be written to support value sets with different column counts?
First, if we had a table that is defined as follows:
CREATE TABLE [Example]
(
[Id] NVARCHAR(10) NOT NULL,
[Name] NVARCHAR(100) NOT NULL,
[Format] NVARCHAR(MAX) DEFAULT('yyyy-MM-dd')
)
Is it somehow possible to create a single MERGE statement which supports entries with and without the format column?
Can the following be adjusted to work?
MERGE [Example] AS t
USING
(
VALUES
('id1', 'England', 'dd/MM/yyyy'),
('id2', 'Germany'), -- The expectation is that the default value would be used
('id3', 'America', 'MM.dd.yyyy')
) AS s([Id], [Name], [Format])
ON
s.[Id] = t.[Id]
WHEN MATCHED THEN
UPDATE SET
t.[Name] = s.[Name],
t.[Format] = s.[Format]
WHEN NOT MATCHED THEN
INSERT ([Id], [Name], [Format])
VALUES (s.[Id], s.[Name], s.[Format]);
This doesn't work because the Germany entry only has 2 values, which does not match the defined column count. I've tried adding ('id2', 'Germany', NULL)
but that inserts a NULL
and not the default value defined for the column. I've also tried adding ('id2', 'Germany', DEFAULT)
but that failed with a Syntax error.
Is what I'm after possible? The only solution I have so far is to maintain two separte MERGE statements, one with the Format column, one without - is there any way to bring them together?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论