【发布时间】:2021-05-12 18:40:11
【问题描述】:
我的存储过程总是返回 0。我尝试了唯一数据并进行了复制,但插入成功完成,但返回值始终相同 @new_identity = 0
CREATE PROCEDURE [dbo].[spAddAuthor]
@Author tyAuthor READONLY,
@new_identity INT = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- check if the author exists
IF NOT EXISTS (SELECT Id_Author FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM @Author)
OR dbo.Authors.phone = (SELECT phone FROM @Author)
OR dbo.Authors.email = (SELECT email FROM @Author)))
BEGIN
INSERT INTO dbo.Authors (Username, sexe, email, phone, address)
SELECT [Username], [sexe], [email], [phone], [address]
FROM @Author
-- output the new row
SELECT @new_identity = @@IDENTITY;
END
ELSE
BEGIN
-- get the author Id if already exists
SELECT @new_identity = (SELECT TOP 1 Id_Author
FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM @Author)
OR dbo.Authors.phone = (SELECT phone FROM @Author)
OR dbo.Authors.email = (SELECT email FROM @Author)))
END
END
【问题讨论】:
-
我建议使用
SCOPE_IDENTITY()而不是其他任何东西(例如@@IDENTITY来获取新插入的标识值。See this blog post for an explanation as to WHY。另外 - 你确定吗?你的表Authors实际上有一个INT IDENTITY列吗? -
Username = (SELECT Username FROM @Author)会失败,如果 TVP 中有超过 1 行,则应将=更改为IN。或者更好的是,将其作为正确的连接JOIN @Author tvp ON tvp.Username = a.Username OR tvp.phone = a.phone OR tvp.email = a.email)并使用表别名来使您的代码更具可读性。 -
用户名在@charlieface 表中是唯一的。并感谢您的建议
-
我试过scope_identety,结果是一样的。但我的目标是如果不存在则插入新行,如果新行返回 id 或返回 id。如果行已经存在,scope_identety 可以获取现有行的 id 吗?对不起我的英语
-
任何情况下您都需要返回 多个 ID,因为您的 TVP 可能有多行。因此,不要在参数中返回单个值,而是将
INSERT和UPDATE更改为 includeOUTPUT inserted.AuthorID
标签: sql-server-2008 stored-procedures