0

我有一张桌子:

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

4 回答 4

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
于 2012-05-09T16:07:27.590 回答
1

您还可以使用 UNION,这可能会或可能不会增加查询的可读性,具体取决于您询问的对象。我发现 CASE 语句或临时表解决方案更具可读性。

select @val1=val from where id=@id1 
UNION
select @val2=val from where id=@id2 
于 2012-05-09T17:39:16.180 回答
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
于 2012-05-09T16:00:20.283 回答
0

怎么样?

select (select @val1=val from where id=@id1) as val1,
(select @val2=val from where id=@id2) as val2
于 2012-05-09T16:03:03.233 回答