结合2个简单的SQL Server查询?

时间:2012-05-09 15:55:03

标签: sql-server sql-server-2008 tsql

我有一张桌子:

id | Val
____________
1  | a
2  | s
3  | e
4  | f
5  | h

我有一个接受2个参数的查询:

@id1 int
@id2 int

此查询有2个内部变量:

@val1 int
@val2 int

我需要将值设置为这些变量:例如 -

select @val1=val from where id=@id1
select @val2=val from where id=@id2

我想用一个查询来做...我试过了:

select @val1=val , @val2=val  
from  table
where id=@id2 or  id=@id1

问题是:

仅当@val1

时,

val才会设置为id=@id1

仅当@val2

时,

val才会设置为id=@id2

(当id = @ id1时@ val2怎么样?它会得到什么值?)

如何在1中编写这2个查询?

4 个答案:

答案 0 :(得分:1)

SELECT 
      @val1=CASE WHEN id=@id1 THEN Val ELSE @val1 END
    , @val2=CASE WHEN id=@id2 THEN Val ELSE @val2 END
FROM table
WHERE ID IN (@id1, @id2)

测试一下:

CREATE TABLE #tmp (ID INT, VAL CHAR(1))
INSERT INTO #tmp VALUES (1,'a')
INSERT INTO #tmp VALUES (2,'s')
INSERT INTO #tmp VALUES (3,'e')
INSERT INTO #tmp VALUES (4,'f')
INSERT INTO #tmp VALUES (5,'h')

DECLARE @id1 INT=1
DECLARE @id2 INT=4

DECLARE @val1 CHAR(1)
DECLARE @val2 CHAR(1)

SELECT 
      @val1=CASE WHEN id=@id1 THEN Val ELSE @val1 END AS Val1
    , @val2=CASE WHEN id=@id2 THEN Val ELSE @val2 END AS Val2
FROM #tmp
WHERE ID IN (@id1, @id2)

SELECT @val1, @val2  --Returns a, f

DROP TABLE #tmp

答案 1 :(得分:1)

您还可以使用UNION,根据您的要求,可能会或可能不会增加查询的可读性。我发现它对CASE语句或临时表解决方案更具可读性。

select @val1=val from where id=@id1 
UNION
select @val2=val from where id=@id2 

答案 2 :(得分:0)

它会对你有用吗?

select @val1=val1 , @val2=val2 
FROM
(
select  
MAX(CASE WHEN id = @id1 THEN val END) AS val1,
MAX(CASE WHEN id = @id2 THEN val END) AS val2  
from  table 
where id=@id2 or  id=@id1 
)a

答案 3 :(得分:0)

怎么样?

select (select @val1=val from where id=@id1) as val1,
(select @val2=val from where id=@id2) as val2