Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

function to return in case of non matching records

$
0
0

Hi

CREATE TABLE [dbo].[DeptMaster](
	[DeptId] [int] NULL,
	[DeptName] [nvarchar](50) NULL
) ON [PRIMARY]

Insert into DeptMaster values
(1,'HeadOffice'),
(2,'BranchOffice'),
(3,'')

CREATE FUNCTION [dbo].[GetDepartmentId]
( 
	@DepartmentNameIn nvarchar(128) 
)
RETURNS int
AS
BEGIN
	DECLARE @DepartmentId INT 
	SELECT @DepartmentId = [DeptId] from DeptMaster where LTRIM(RTRIM([DeptName])) =  @DepartmentNameIn  
	If @DepartmentId <0		BEGIN
			SELECT @DepartmentId = [DeptId] from DeptMaster where LTRIM(RTRIM([DeptName])) =  ''
		END
	RETURN @DepartmentId
END


select  dbo.GetDepartmentId ('BranchOffice')  -- will return 2, correct
select  dbo.GetDepartmentId ('DivisonalOffice')  --- expected 3 ... need to alter my Function so that 3 is returned.
select  dbo.GetDepartmentId ('SubOffice')  --- expected 3 ... need to alter my Function so that 3 is returned.

-- Reason, Whenever i get data which is not passed, i need to return the 3

kindly suggest how to pass into the  If @DepartmentId <0 as  i get 0 records if no data is found matching


ShanmugaRaj


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>