5

How do I implement boolean logic in the select statement while the query is running?

SELECT t.[Key]
      ,t.[Parent_Key]
      ,t.[Parent_Code]
      ,t.[Code]
      ,t.[Desc] 
      ,t.[Point]
      ,[isChild] -- If Point > 2, then true, if Point == 1 Then false   
      ,t.[By] 
      ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter

I want make some logic to determine [isChild] boolean value based on t.[Point]

John Conde
  • 217,595
  • 99
  • 455
  • 496
Ramie
  • 1,171
  • 2
  • 16
  • 35

4 Answers4

5
SELECT t.[Key]
      ,t.[Parent_Key]
      ,t.[Parent_Code]
      ,t.[Code]
      ,t.[Desc] 
      ,t.[Point]
      ,CASE WHEN t.[Point] > 2 THEN 1 ELSE  
            CASE WHEN t.[Point] = 1 THEN 0 ELSE NULL END 
       END AS [isChild]
      ,t.[By] 
      ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter

Be aware that when t.[Point] < 1 then [isChild] will be null

Jarek Bielicki
  • 856
  • 6
  • 16
1

Case is your friend...

 SELECT Key, Parent_Key, Parent_Code, Code, Desc, point, 
     case when point > 2 then 1 
          when point = 1 then 0 end isChild, 
     [By], [On]
 FROM db.stats  
 WHERE Parent_Key= @tmpParameter
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

Use the case statement:

SELECT t.[Key]
      ,t.[Parent_Key]
      ,t.[Parent_Code]
      ,t.[Code]
      ,t.[Desc] 
      ,t.[Point]
      ,CASE t.[Point] WHEN 1 THEN FALSE WHEN 2 THEN TRUE END as [isChild]
      ,t.[By] 
      ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
0

You can use CASE statement

SELECT t.[Key]
  ,t.[Parent_Key]
  ,t.[Parent_Code]
  ,t.[Code]
  ,t.[Desc] 
  ,t.[Point]
  ,CASE 
  WHEN t.[Point] THEN true 
  else false
  END as isChild
  ,t.[By] 
  ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter
Nebojsa Susic
  • 1,220
  • 1
  • 9
  • 12