dev2d
dev2d

Reputation: 4262

Why my SQL Function returns unexpected value?

I am writing a function where I need to fetch Title(e.g. Mr/Miss/Mrs) FirstName and LastName from a table based on a comma delimited string containing user emails.

so far I have tried following

My SQL Fiddle PS. First build the schema on fiddler page and then try to executing queries

When i run following

select dbo.fn_getUserNamefrmEmail('[email protected]')

I get proper output as Mr. Abc Def

but when i try to run

select dbo.fn_getToUserNames('[email protected], [email protected], [email protected], [email protected]',',')

I am getting NULL - 0 as i have set result to 0 if it is NULL

I am unable to understand what am I doing wrong and need help.

Upvotes: 2

Views: 192

Answers (1)

Szymon
Szymon

Reputation: 43023

There is only one small problem.

Change the line

DECLARE @result_string nvarchar(max)

to

DECLARE @result_string nvarchar(max) = ''

You haven't initialised @result_string variable so it remains null when you do

SELECT @result_string = @result_string + ', ' + @temp

And the end result is still null.

Correct version in SQL Fiddle.

Upvotes: 5

Related Questions