Select Case with Integer that could be null (1 Viewer)

Rx_

Nothing In Moderation
Local time
Today, 13:25
Joined
Oct 22, 2009
Messages
2,803
Select Case statement - fragment of a function
How are Nulls handled for both Select Case and return of a Char (string) in T-SQL.

Didn't look like anyone responded just yet.
Forgot - can't use SELECT (with case) inside a scalar function - error message - back to the drawing board!

Have not run this just yet and realize it is a bit verbose.
Just wondering about how a Null is going to be treated in this case.
It is the little things that matter
Code:
--   Function not shown, passes in @ID_Wells as argument
DECLARE @SurfaceOwnerID as Int
DECLARE @CharResult as varchar(14)
DECLARE @TestValue INT
set @SurfaceOwnerID = (SELECT Wells_Lease.ID_Wells, Wells_Lease.SurfaceOwnerID
						FROM Wells_Lease
						WHERE                    (((Wells_Lease.ID_Wells)=@ID_Wells))
						)

 SET @TestValue = @SurfaceOwnerID -- Value 1 to 10 including Null
 SELECT
   CASE @TestValue
     WHEN 1 THEN @CharResult = 'First'
     WHEN 2 THEN @CharResult  = 'Second'
     WHEN 3 THEN @CharResult = 'Third'
  ELSE @CharResult = Null
 END

My plan is to try this and trouble shoot it. Any suggestions are welcome. There always seems to be some innovative option in T-SQL
 
Last edited:

Rx_

Nothing In Moderation
Local time
Today, 13:25
Joined
Oct 22, 2009
Messages
2,803
At least this compiles - no idea if it performs as intended.
Using a Select Case in a scalar function generated an error that it isn't allowed.

We will see how this works - any suggestions are more than welcome

Code:
CREATE FUNCTION [dbo].[vReg_Nav_Data_Permit-TopSurfaceOwner](@ID_Wells as Int) 
RETURNS varchar(14)  --Returen top value of Allotted, Tribal or FED - else null
AS 
BEGIN; 
  DECLARE @SurfaceOwnerID as Int
  DECLARE @CharResult as varchar(14)
  DECLARE @CharReturnValue as varchar(14)

  set @SurfaceOwnerID = (SELECT  Wells_Lease.SurfaceOwnerID
						FROM Wells_Lease
						WHERE (((Wells_Lease.ID_Wells)=@ID_Wells))
						)

SET @CharResult = CASE 
WHEN @SurfaceOwnerID = 10 THEN 'Allotted' 
WHEN @SurfaceOwnerID = 4 THEN 'Tribal' 
WHEN @SurfaceOwnerID = 1 THEN 'Federal' 
ELSE null 
END  -- end else

Set @CharReturnValue = @CharResult
 return @CharReturnValue		-- Text value returned by function
END; 
GO

Yep, this one works.
In my case, just luck the 10, 4, 1 were in order of importance for the solution. 10 trumps, 4 that trumps 1 - the rest return null.
 
Last edited:

Users who are viewing this thread

Top Bottom