My stored procedure always returns 0. I tried unique data and duplicated but the insert is done with success but the return value is always the same @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()
instead of anything else (like@@IDENTITY
to grab the newly inserted identity value. See this blog post for an explanation as to WHY. Also - are you sure that your tableAuthors
does in fact have anINT IDENTITY
column at all?Username = (SELECT Username FROM @Author)
is going to fail if there is more than one row in the TVP, you should change=
toIN
. Or better, do it as a proper joinJOIN @Author tvp ON tvp.Username = a.Username OR tvp.phone = a.phone OR tvp.email = a.email)
and use table aliases to make your code more readable.INSERT
andUPDATE
to includeOUTPUT inserted.AuthorID