2013-08-06 3 views
2

У меня есть следующий запрос:Как сохранить результат запроса sql в переменной?

with cte as 
(SELECT top 10 [1],[2] 
FROM [tbl_B] where [2] > '2000-01-01' and Status_7 = 0 and   Status_8 = 1 
ORDER BY [2]) 
, 
CTE1 AS 
(select [1], row_number() over (order by [2]) as rn 
from CTE 
) 
select [1] from CTE1 where rn = '10' 

как я могу поместить это в переменную, чтобы сравнить его с другим результатом запроса? Если я использую set @ 123 = (выше запроса), он дает ошибки.

ответ

2
with cte as 
(
    SELECT top 10 [1],[2] 
    FROM [tbl_B] 
    where [2] > '2000-01-01' and Status_7 = 0 and Status_8 = 1 
    ORDER BY [2] 
) 
,CTE1 AS 
( 
    select [1], row_number() over (order by [2]) as rn 
    from CTE 
) 
select @123 = [1] from CTE1 where rn = '10' 
+0

В небольшой заметке, в то время как 'SET @ 123 =' будет «взорваться», если есть более чем строка, 'SELECT @ 123 =' будет выполняться без проблем и поместить значение последней строки. – xanatos

0
with cte as 
(SELECT top 10 [1],[2] 
FROM [tbl_B] where [2] > '2000-01-01' and Status_7 = 0 and   Status_8 = 1 
ORDER BY [2]) 
, 
CTE1 AS 
(select [1], row_number() over (order by [2]) as rn 
from CTE 
) 
select @123 = [1] from CTE1 where rn = '10' 
0

Вы можете использовать табличную переменную для хранения результирующего набора КТР в. Например:

declare @table_var table (id int, col1 varchar(50)); 

; with CTE as 
     (
     ... your definition here ... 
     ) 
insert @table_var 
     (id, col1) 
select id 
,  col1 
from CTE 

Сравнивая это с другим набором может быть сделано с полным внешним соединением:

select coalesce(t1.id, t2.id) as id 
,  coalesce(t1.col1, t2.col1) as col1 
,  case 
     when t1.id is null then 'Missing in t1' 
     when t2.id is null then 'Missing in t2' 
     when isnull(t1.col1,'') <> isnull(t2.col1,'') then 'Col1 is different' 
     else 'Identical' 
     end as Difference 
from @table_var1 t1 
full outer join 
     @table_var2 t2 
on  t1.id = t2.id 
Смежные вопросы