I've been trying to execute the next sp. My target is to generate a string with the values of several ID. This is what I've done:
ALTER PROCEDURE SP_IDENTIF @ID NVARCHAR OUTPUT
AS
BEGIN
DECLARE
@DATUM NVARCHAR(MAX),
@CONCAT NVARCHAR(MAX),
@IDENTIFIC NVARCHAR(MAX),
@T DATETIME ;
SET @IDENTIFIC = '';
DECLARE IDENTIFIERS CURSOR LOCAL FOR
SELECT TOP 2 ID
FROM TABLE_1
WHERE ID IS NOT NULL
UNION
SELECT TOP 2 ID
FROM TABLE_2
WHERE ID IS NOT NULL
OPEN IDENTIFIERS
FETCH NEXT FROM IDENTIFIERS INTO @DATUM
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @IDENTIFIC;
SELECT @IDENTIFIC = CONCAT(@IDENTIFIC,',OR ID =''',@DATUM,'''');
FETCH NEXT FROM IDENTIFIERS INTO @DATOS;
END;
CLOSE IDENTIFIERS;
SET @ID = @IDENTIFIC;
PRINT('THE IDENTIFIERS ARE: '+@ID);
RETURN;
END
If I execute the union query I will have the next output (obviously the top keyword is just to test the result):
ID
101075330-IC001
ACP-2582785
ACP-645655
ACP-942612
But when I call the sp I am getting the next output:
declare @identific nvarchar(max);
exec sp_Identif @identific output;
print 'The ID set is: '+@identific;
,OR ID ='101075330-IC001'
,OR ID ='101075330-IC001',OR ID ='ACP-2582785'
,OR ID ='101075330-IC001',OR ID ='ACP-2582785',OR ID ='ACP-645655'
THE IDENTIFIERS ARE : ,
The ID set is :
I am printing the result of the variable @identif and @Id to check what is going on with its value. As you can see can see only 3 Id's inserted in the string variable durint the fetch loop, but at the end of the cycle I do not have any value recordint in the output variable.
What am I doing wrong with this code?, and is there another way to reach the same target?. I am trying to implement a SP that is going to be called from SSIS.
Thanks