开发者

Error when using INSERT INTO with SELECT

I'm trying to compile this stored procedure on MSSQL:

ALTER PROCEDURE [dbo].[sp_Notice_insert]
    @type text,
    @message text
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO tbl_Notices (id, type, message)
    VALUES (NewID(), @type, @message);

    DECLARE @noticeid uniqueidentifier;
    SET @noticeid = SCOPE_IDENTITY();

    INSERT INTO tbl_NoticesInbox (userid, noticeid)
    (SELECT id, @noticeid FROM tbl_User WHERE role='Staff');

END
GO

It should insert a "notice" into one table then insert a "notification" into the inbox table, for every 'Staff' user. But when compiling I get this error:

Operand type clash: numeric is incompatible with uniqueidentifier

开发者_如何学JAVA

The 'role' field is nbarchar(10) so I tried N'Staff' as the value too but I get the same error. It doesn't say which types are actually clashing. What am I doing wrong?


The problem is that SCOPE_IDENTITY() returns the last value entered into an IDENTITY column within the current scope, and therefore by default returns a numeric value.

It looks to me like you want to create a NEWID() and use that both to insert the header and related records:

DECLARE @noticeid uniqueidentifier;
SET @noticeid = NEWID();

INSERT INTO tbl_Notices (id, type, message)
VALUES (@noticeid , @type, @message);

INSERT INTO tbl_NoticesInbox (userid, noticeid)
(SELECT id, @noticeid FROM tbl_User WHERE role='Staff');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜