Problems with the execution of a sp in sql

2019-09-09 00:41发布

问题:

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

回答1:

Your main problem is that @ID NVARCHAR is equivalent to @ID NVARCHAR(1) and you are getting truncation.

You don't need a cursor here either and the sp_ prefix should be avoided as it is reserved for Microsoft system procedures.

The following would return an output of

,OR ID ='101075330-IC001',OR ID ='ACP-2582785',OR ID ='ACP-645655',OR ID ='ACP-942612'

from your example input

CREATE PROCEDURE dbo.usp_IDENTIF (@ID NVARCHAR(MAX) OUTPUT)
AS
  BEGIN
      WITH T(ID)
           AS (SELECT ID
               FROM   TABLE_1
               WHERE  ID IS NOT NULL
               UNION
               SELECT ID
               FROM   TABLE_2
               WHERE  ID IS NOT NULL)
      SELECT @ID = CAST((SELECT CONCAT(',OR ID =''', ID, '''')
                         FROM   T
                         FOR XML PATH('')) AS NVARCHAR(MAX))
  END