如何在变量中存储sql查询的结果?

时间:2013-08-06 08:41:57

标签: 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 =(上面的查询),则会出错。

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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'

答案 2 :(得分:0)

您可以使用表变量来存储CTE的结果集。例如:

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