在插入记录之前迭代 TVP?

发布于 2024-11-06 12:03:23 字数 287 浏览 6 评论 0原文

我需要一些帮助来编写以下存储过程:

我有 SQL Server 2008 存储过程,它接受两个整数值(@ID1 和 @ID2)和一个数据表/TVP。

TVP表包含几个字段,即。标题和描述。

我想迭代 TVP 表并检查标题或描述是否已存在于我的数据表 tbl_Items 中,其中 @ID1 = tbl_Items.ID1 和 @ID2 = tbl_Items.ID2。

如果两者都不存在,则将 @ID1 和 ID2 的值以及该 TVP 行插入到 tbl_Items 中。

谢谢。

I'd like some help writing the following sproc:

I have SQL Server 2008 sproc that accepts two integer values (@ID1 and @ID2) and a data table/TVP.

The TVP table contains several fields, ie. Title and Description.

I want to iterate through the TVP table and check if the Title or Description already exists in my data table, tbl_Items, where @ID1 = tbl_Items.ID1 and @ID2 = tbl_Items.ID2.

If neither exist then insert the values of @ID1 and ID2 and that TVP row into tbl_Items.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安人多梦 2024-11-13 12:03:23

像这样的东西吗?

INSERT INTO tbl_Items (ID1, ID2, Title, Description)
  SELECT
    @ID1, @ID2, TVP.Title, TVP.Description
  FROM
    @TVP AS TVP
  WHERE
    NOT EXISTS (SELECT * FROM tbl_Items AS I WHERE TVP.Title = I.Title AND TVP.Description = I.Description)

Something like this?

INSERT INTO tbl_Items (ID1, ID2, Title, Description)
  SELECT
    @ID1, @ID2, TVP.Title, TVP.Description
  FROM
    @TVP AS TVP
  WHERE
    NOT EXISTS (SELECT * FROM tbl_Items AS I WHERE TVP.Title = I.Title AND TVP.Description = I.Description)
岁月静好 2024-11-13 12:03:23

要求似乎有些不清楚,但您应该能够使用 MERGE

;WITH Target As
(
SELECT * 
FROM tbl_Items 
WHERE ID1=@ID1 AND ID2=@ID2
)
MERGE 
    INTO Target
    USING @TVP AS Source
    ON Target.Title = Source.Title OR Target.Description = Source.Description
    WHEN NOT MATCHED 
        THEN INSERT  (ID1, ID2, Title, Description) 
              VALUES (@ID1, @ID2, Title, Description)

The requirement seems somewhat unclear but you should be able to use MERGE

;WITH Target As
(
SELECT * 
FROM tbl_Items 
WHERE ID1=@ID1 AND ID2=@ID2
)
MERGE 
    INTO Target
    USING @TVP AS Source
    ON Target.Title = Source.Title OR Target.Description = Source.Description
    WHEN NOT MATCHED 
        THEN INSERT  (ID1, ID2, Title, Description) 
              VALUES (@ID1, @ID2, Title, Description)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文