2

I have the following query:

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'

how can I put this into a variable to compare it to another query result? If i use set @123 = (above query) it gives errors.

4

3 回答 3

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'
于 2013-08-06T08:45:03.363 回答
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'
于 2013-08-06T08:44:36.520 回答
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
于 2013-08-06T08:52:20.167 回答