Hi all!
I'm new to SQL but I have a function that isn't returning a value like it should and I'm hoping that someone can help. The code:
CREATE OR ALTER FUNCTION [ccdd].[fn_DemographicsLookup](@input VARCHAR(100), @colName VARCHAR(100))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @str NVARCHAR(1000)
DECLARE @tab TABLE (item VARCHAR(50))
DECLARE @rts NVARCHAR(1000)
DECLARE @xml XML
DECLARE @num INT
SET @str = ''
set @rts = ''
IF @input = ''
BEGIN
RETURN NULL
END
SET @xml = N'<t>' + REPLACE(@input,'&','</t><t>') + '</t>'
INSERT INTO @tab
SELECT r.value('.','int') as item
FROM @xml.nodes('/t') as records(r)
SELECT @str = (CONCAT( COALESCE(@str,''),STUFF((SELECT ' ' + item + ','
FROM @tab
FOR XML PATH('')) ,1,1,'')))
SELECT @str = TRIM(',' FROM @str)
SELECT @rts = @rts + CONCAT(COALESCE(@colName,''),'|') FROM prod_test.ccdd.DemographicsLookup dl WHERE dl.id IN (SELECT * FROM STRING_SPLIT(@str,','))
SET @rts = TRIM( '|' FROM @rts)
RETURN @rts
END
When I execute the function
exec ccdd.fn_DemographicsLookup @input = '2&3', @colName = 'nutrition'
I get the following:
(2 rows affected)
Completion time: 2022-06-29T19:25:26.9266291-04:00
However when I run the code outside the function like so:
DECLARE @str VARCHAR(1000)
DECLARE @tab TABLE (item varchar(50))
DECLARE @rts VARCHAR(1000)
DECLARE @xml XML
DECLARE @num INT
SET @str = ''
set @rts = ''
-- IF @input = ''
-- BEGIN
--RETURN NULL
-- END
SET @xml = N'<t>' + REPLACE('2&3&5','&','</t><t>') + '</t>'
INSERT INTO @tab
SELECT r.value('.','int') as item
FROM @xml.nodes('/t') as records(r)
SELECT @str = (CONCAT( COALESCE(@str,''),STUFF((SELECT ' ' + item + ','
FROM @tab
FOR XML PATH('')) ,1,1,'')))
SELECT @str = TRIM(',' FROM @str)
SELECT @rts = @rts + CONCAT(COALESCE(nutrition,''),'|') FROM prod_test.ccdd.DemographicsLookup dl WHERE dl.id IN (select * from string_split(@str,','))
SELECT @rts = TRIM( '|' FROM @rts)
SELECT @rts
I get the correct result:
(No column name)
Requires modified consistency diet for foods|Requires modified consistency diet for fluids|Requires high calorie diet
Could someone please help?? Thanks in advance