开发者

what is the best way to return a auto created guid id?

开发者 https://www.devze.com 2022-12-17 09:44 出处:网络
I have a table that has a newid() for the primary key field (Id) in the stored procedure i need to return this newly created guid开发者_如何学JAVA back as a return parameter, i could create the guid

I have a table that has a newid() for the primary key field (Id)

in the stored procedure i need to return this newly created guid开发者_如何学JAVA back as a return parameter, i could create the guid beforehand and insert into the database, but that would defeat the purpose of a newid(). Is there a good way to handle this?

INSERT INTO [SUBS].[dbo].[Subscriptions]
           ([CustomerId]
           ,[SubscriptionClassId]
           ,[StartDate]
           ,[TrialAmount]
           ,[Amount]
           ,[TrialInterval]
           ,[Interval]
           ,[TrialIntervalLength]
           ,[IntervalLength]
           ,[CreatedBy]
           ,[LastUpdatedBy])
     VALUES
           (@CustomerId
           ,@SubscriptionClassId
           ,@StartDate
           ,@TrialAmount
           ,@Amount
           ,@TrialInterval
           ,@Interval
           ,@TrialIntervalLength
           ,@IntervalLength
           ,@CreatedBy
           ,@CreatedBy)

select @SubscriptionId = SCOPE_IDENTITY() -- this does not work because scope_identity is numeric


I haven't actually tested this, but if you're using a later version of SQL server you can use output statements:

DECLARE @ins TABLE (id uniqueidentifier)

INSERT INTO [SUBS].[dbo].[Subscriptions] 
           ([CustomerId] 
           ,[SubscriptionClassId] 
           ,[StartDate] 
           ,[TrialAmount] 
           ,[Amount] 
           ,[TrialInterval] 
           ,[Interval] 
           ,[TrialIntervalLength] 
           ,[IntervalLength] 
           ,[CreatedBy] 
           ,[LastUpdatedBy]) 
     OUTPUT INSERTED.id INTO @ins (id)
     VALUES 
           (@CustomerId 
           ,@SubscriptionClassId 
           ,@StartDate 
           ,@TrialAmount 
           ,@Amount 
           ,@TrialInterval 
           ,@Interval 
           ,@TrialIntervalLength 
           ,@IntervalLength 
           ,@CreatedBy 
           ,@CreatedBy) 

select @SubscriptionId = id from @ins

Otherwise you'd need to create an identity column on the subscriptions table and then use that as a lookup to select the id out.


The output of newid() can be casted to a string value.

Use CAST(NEWID() AS varchar(36)) to get a GUID string.

0

精彩评论

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