Définir la valeur de la variable dans le server SQL

Declare @CategoryID as int BEGIN SELECT (CASE WHEN EXISTS( SELECT t0.Categoryid AS [EMPTY] FROM Categories AS [t0] WHERE [t0].Categoryname = @CategoryName ) THEN 1 ELSE 0 END) AS [value] 

si je veux définir ma variable à l'intérieur du bloc existe avec t0.Categoryid comment pourrais-je faire cela?

ce que je veux est de replace puis 1 à la valeur d'id de catégorie …

Merci d'avance..

 Declare @CategoryID as int SET @CategoryID = CASE WHEN EXISTS(SELECT 1 FROM Categories WHERE Categoryname = @CategoryName) THEN 1 ELSE 0 END 

Une autre façon serait quelque chose comme ….

 IF EXISTS (SELECT 1 FROM Categories WHERE Categoryname = @CategoryName) BEGIN SET @CategoryID = 1; END ELSE BEGIN SET @CategoryID = 0; END 

Cela renverra l'identifiant de catégorie, s'il existe, et 0 s'il ne l'est pas.

 SET @CategoryID = null; SELECT @CategoryID = t0.Categoryid FROM Categories AS [t0] WHERE [t0].Categoryname = @CategoryName; IF @CategoryID IS NULL SET @CategoryID = 0; SELECT @CategoryID AS [value]; 

Cependant, je reorderais simplement de returnner null si elle n'existe pas, ou de renvoyer un autre @Exists (BIT) pour indiquer si elle existe ou non.

Vous pouvez essayer comme ça.

 Declare @CategoryID as int Set @CategoryID =0; SELECT @CategoryID=t0.Categoryid FROM Categories AS [t0] WHERE [t0].Categoryname = @CategoryName 

Nom de la catégorie IF Existe en assignant la catégorie Id de cette catégorie sinon elle rest nulle.

 Declare @CategoryID as int SET @CategoryID = (SELECT t0.Categoryid AS [EMPTY] FROM Categories AS [t0] WHERE [t0].Categoryname = @CategoryName) SET @CategoryID =COALESCE(@CategoryID ,0) 

Mes 2 cents …

 DECLARE @any BIT = 0 SELECT TOP 1 @any = 1 FROM Categories WHERE CategoryName = @CategoryName IF (@any = 1) PRINT 'Yes' ELSE PRINT 'No'