Wednesday, March 21, 2012

how do I get the uniqueidentifier of just inserted row?

Hello there!

it was a while since i studied SQL and that brings us to my problem...

I'm creating a Stored Procedure wich first insert information in a table. That table has a uniqueidentifier fild that is default-set to newid().

later in the SP i need that uniqueidentifier value? how do I get it?

I tried this:

CREATE PROCEDURE spInsertNews
@.uidArticleId uniqueidentifier = newid,
@.strHeader nvarchar(300),
@.strAbstract nvarchar(600),
@.strText nvarchar(4000),
@.dtDate datetime,
@.dtDateStart datetime,
@.dtDateStop datetime,
@.strAuthor nvarchar(200),
@.strAuthorEmail nvarchar(200),
@.strKeywords nvarchar(400),
@.strCategoryName nvarchar(200) = 'nyhet'
AS
INSERT INTO tblArticles
VALUES( @.uidArticleId,@.strHeader,@.strAbstract,@.strText,@.dt Date,@.dtDateStart,@.dtDateStop,@.strAuthor,@.strAutho rEmail,@.strKeywords)

declare @.uidCategoryId uniqueidentifier
EXEC spGetCategoryId @.strCategoryName, @.uidCategoryId OUTPUT

INSERT INTO tblArticleCategory(uidArticleId, uidCategoryId)
VALUES(@.uidArticleId, @.uidCategoryId)

But i get an error when I EXEC the SP like this:

EXEC spInsertNews
@.strHeader = 'Detta r den andra nyheten',
@.strAbstract = 'dn frsta insatt med sp:n',
@.strText = 'hr kommer hela nyhetstexten att st. Hr fr det plats 2000 tecken, dvs fler n vad jag orkar skriva nu...',
@.dtDate = '2003-01-01',
@.dtDateStart = '2003-01-01',
@.dtDateStop = '2004-01-01',
@.strAuthor = 'David N',
@.strAuthorEmail = 'david@.davi.com',
@.strKeywords = 'nyhet, blajblaj, blaj'

the errormessage is: Syntax error converting from a character string to uniqueidentifier.

does anyone have a sulution to this problem?
Can I use something similar to the @.@.IDENTITY?
I will be greatful for any ideas...

thanks
/David, SwedenNever mind...

i solved it.

Here's the working code...

CREATE PROCEDURE spInsertNews
@.strHeader nvarchar(300),
@.strAbstract nvarchar(600),
@.strText nvarchar(4000),
@.dtDate datetime,
@.dtDateStart datetime,
@.dtDateStop datetime,
@.strAuthor nvarchar(200),
@.strAuthorEmail nvarchar(200),
@.strKeywords nvarchar(400),
@.strCategoryName nvarchar(200) = 'nyhet'
AS
DECLARE @.uidArticleId uniqueidentifier
SET @.uidArticleId = newid

INSERT INTO tblArticles
VALUES( @.uidArticleId,@.strHeader,@.strAbstract,@.strText,@.dt
Date,@.dtDateStart,@.dtDateStop,@.strAuthor,@.strAutho
rEmail,@.strKeywords)

declare @.uidCategoryId uniqueidentifier
EXEC spGetCategoryId @.strCategoryName, @.uidCategoryId OUTPUT

INSERT INTO tblArticleCategory(uidArticleId, uidCategoryId)
VALUES(@.uidArticleId, @.uidCategoryId)sql

No comments:

Post a Comment