1

我有一个由应用程序的其他部分提供的复杂查询,我需要添加一个常量列并传递查询以进行进一步处理(SSRS ServerReport)。查询可以由多个查询组成,UNION ALL并且可以包含ORDER BY.

编辑:我忘记强调标题中包含的内容而不进行解析。我对查询(条件、子查询)一无所知,所以解析和修改它是相当危险的。

例子:

declare @t table(id int)
insert into @t values(1)
insert into @t values(2) 

查询:

(select  id from @t where id=1
union all
select  id from @t where id=2) order by id desc

所需输出:

id | Par
----------
2  | Hello   
1  | Hello

尝试(不使用 ORDER BY):

SELECT *, 'Hello' Par from
((select  id from @t where id=1
    union all
    select  id from @t where id=2) order by id desc) tbl

解决方案必须适用于 SQL Server 2008+。

4

6 回答 6

1
select tbl.id,
    'Hello' Par
from (
    select id
    from @t
    where id = 1

    union all

    select id
    from @t
    where id = 2
 ) tbl
order by tbl.id desc

我假设您正在 UNIONing 与您的示例不同的查询,否则您只需执行以下操作:

select id,      
   'Hello' Par
from @t
where id in (1, 2)
order by id desc
于 2012-04-23T14:12:57.423 回答
1

如果不注入查询(或创建像@satcat66 的答案这样的详细动态 SQL),您将无法解决此问题。带有联合的子查询需要一个别名来定义它,例如where id=2) AS alias ORDER BY id DESC)...,没有任何魔法可以使这种损坏的语法起作用。

于 2012-04-23T15:03:20.997 回答
0
declare @t table(id int)
insert into @t values(1)
insert into @t values(2) 

;WITH cte AS(
    SELECT id, 'Hello' Par
     FROM @t t1 WHERE t1.id=1

    UNION ALL

    SELECT id, 'Hello' Par
    FROM @t t2 WHERE t2.id=2
)
SELECT * FROM cte
ORDER BY id DESC

WITH common_table_expression

于 2012-04-23T14:14:07.097 回答
0

如何使用 CTE:

declare @t table(id int)
insert into @t values(1)
insert into @t values(2) 
;
with my_cte as (
    select  id from @t where id=1
    union all
    select  id from @t where id=2
)
select *, 'Hello'
from my_cte
order by id

编辑:在这种情况下,您可以在临时表中插入主查询的结果。它将尊重排序:

create table #temptable(
id int
)

declare @t table(id int)
insert into @t values(1)
insert into @t values(2) 

insert into #temptable
select  id from @t where id=1
union all
select  id from @t where id=2
order by id desc

select *, 'Hello' from #temptable

结果:

2   Hello
1   Hello
于 2012-04-23T14:18:16.110 回答
0

你的查询有点问题

SELECT *, 'Hello' Par from
(select  id from @t where id=1
    union all
    select  id from @t where id=2) tbl order by id desc
于 2012-04-23T14:22:38.097 回答
0

假设您事先知道列名和类型,

DECLARE @query nvarchar(max);
SET @query = '

declare @t table(id int);
insert into @t values(1);
insert into @t values(2); 
(select  id from @t where id=1
    union all
    select  id from @t where id=2) order by id desc';

 CREATE TABLE #T ( ind int IDENTITY(1,1) NOT NULL, id int );
 INSERT INTO #T (id)
 exec sp_executesql @query;

 SELECT ID, 'Hello' AS Par FROM #T ORDER BY ind;
于 2012-04-23T15:02:16.220 回答