SQL合并与可变的值数

发布于 2025-02-08 15:42:04 字数 987 浏览 3 评论 0原文

我想知道是否可以以某种方式编写合并语句来支持不同的列计数的值集?

首先,如果我们有一个定义如下的表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文