2010-01-14 2 views
0

J'ai une table qui a un newid() pour le champ clé primaire (Id)Quel est le meilleur moyen de renvoyer un identifiant de guidage créé automatiquement?

dans la procédure stockée je dois retourner ce guid nouvellement créé comme un paramètre de retour, je pourrais créer le guid avant et insérer dans la base de données, mais cela irait à l'encontre de l'objectif d'un newid(). Y a-t-il un bon moyen de gérer cela?

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 

Répondre

0

Je ne l'ai pas fait testé, mais si vous utilisez une version ultérieure du serveur SQL, vous pouvez utiliser des instructions de sortie:

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 

Sinon, vous aurez besoin de créer une colonne d'identité sur la table des abonnements, puis utilisez-le comme une recherche pour sélectionner l'ID.

0

La sortie de newid() peut être convertie en une valeur de chaîne. Utilisez CAST(NEWID() AS varchar(36)) pour obtenir une chaîne GUID.

Questions connexes