복붙노트

[SQL] SQL 서버에 대한 변수에 동적 SQL의 결과를 얻기

SQL

SQL 서버에 대한 변수에 동적 SQL의 결과를 얻기

실행 동적 SQL은 저장 프로 시저에서 다음과 같습니다 :

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
SET @city = 'London'
SET @sqlCommand = 'SELECT COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

어떻게 SP에서 반환 값으로 COUNT (*) 열 값을 사용합니까?

해결법

  1. ==============================

    1.

    DECLARE @sqlCommand nvarchar(1000)
    DECLARE @city varchar(75)
    declare @counts int
    SET @city = 'New York'
    SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
    EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
    select @counts as Counts
    
  2. ==============================

    2.당신은 아마이 시도했지만, 당신의 사양은이 작업을 수행 할 수 있도록인가?

    당신은 아마이 시도했지만, 당신의 사양은이 작업을 수행 할 수 있도록인가?

    DECLARE @city varchar(75)
    DECLARE @count INT
    SET @city = 'London'
    SELECT @count = COUNT(*) FROM customers WHERE City = @city
    
  3. ==============================

    3.동적 버전

    동적 버전

        ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
        AS
        BEGIN
            -- Declare the return variable here
           DECLARE @sqlCommand nvarchar(1000)
           DECLARE @maxVal INT
           set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
           EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
           DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
        END
    
    
    exec dbo.ReseedTableIdentityCol @p_table='Junk'
    
  4. ==============================

    4.

    DECLARE @sqlCommand nvarchar(1000)
    DECLARE @city varchar(75)
    DECLARE @cnt int
    SET @city = 'London'
    SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
    EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
    RETURN @cnt
    
  5. ==============================

    5.이 솔루션을 수 있을까?

    이 솔루션을 수 있을까?

    declare @step2cmd nvarchar(200)
    DECLARE @rcount NUMERIC(18,0)   
    set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
    EXECUTE @rcount=sp_executesql @step2cmd
    select @rcount
    
  6. ==============================

    6.

     vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
        AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
        PRINT_STRING(VMYQUERY);
        EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;
    
  7. from https://stackoverflow.com/questions/3840730/getting-result-of-dynamic-sql-into-a-variable-for-sql-server by cc-by-sa and MIT license