3

이 커서를 루핑/재귀 CTE로 변환 할 수있는 방법이 있습니까? CTE 관련 기사를 읽었지만 계층 구조에 관한 기사를 읽었습니다.CTE를 루프로 사용하는 방법은 무엇입니까?

create table #things(id int) 
insert into #things (id) 
values(1),(2),(3),(4),(5) 

create table #items (name varchar(8), id int) 
insert into #items 
values ('grodd', 1), ('duck', 2), ('time', 3), ('nix', 4), ('quasar', 7) 


declare @count int = 0 
declare @id int = 0 
declare @name varchar(8) = null 

-- load cursor with ids from table #things 
declare test_cursor cursor for 
select id 
from #things 

-- get id first row and set @id with id 
open test_cursor 
fetch next from test_cursor into @id 

while @@FETCH_STATUS = 0 
begin 
    set @count = (select count(id) from #items where id = @id) 
    if (@count > 0) 
    begin 
     set @name = (select top 1 name from #items where id = @id) 
     exec dbo.test_stored_procedure @name 
    end 
    -- get id from next row and set @id = id 
    fetch next from test_cursor into @id 
end 

close test_cursor 
deallocate test_cursor 

drop table #items 
drop table #things 

답변

0

절차 대신 함수를 사용할 수 있으면 CTE를 사용할 필요가 없습니다. 당신은 select 절에서 직접 기능을 사용하거나이

select result.* 
from #items as i 
inner join #things as t on t.id = i.id 
cross apply 
dbo.test_stored_function (i.name) as result 

처럼 뭔가를 할 수 또는 당신이 절대적으로 CTE를 사용하려는 경우 다음 당신은 dbo.test_stored_function가 있어야이 경우이 코드

with some_array as (
    select i.name 
    from #items as i 
    inner join #things as t on t.id = i.id 
) 
select result.* from some_array as sa 
cross apply 
dbo.test_stored_function (sa.name) as result 

을 사용할 수 있습니다 테이블 반환 함수 (스칼라가 아님). 위의 예제에서 함수에서 반환되는 열의 하나는 name이라는 이름의 nvarchar이지만 필요로하는 수는 있습니다.

절대적으로 프로 시저를 사용해야하는 경우 동적 SQL 쿼리를 사용해 볼 수 있습니다. 당신은 (결과는 프로 시저 매개 변수에 대한 데이터가 포함 된 다른 SQL 쿼리에 연결 사용) 내부의 여러 쿼리를 하나의 문자열을 준비하고이 예에서와 같이 기능 sp_executesql 그것을 실행할 수

declare @sql nvarchar(max) = N'execute dbo.some_procedure val1; execute dbo.some_procedure val2;'; 
execute sp_executesql @sql; 

당신은 기능 sp_executesql에 대한 자세한 내용을보실 수 있습니다 여기 : https://msdn.microsoft.com/pl-pl/library/ms188001%28v=sql.110%29.aspx?f=255&MSPPError=-2147217396