1

我有下表(假设它的名称是“AnswerTable”:

QuestionID Value
100        1
101        2
102        1
103        2
104        1
105        2
...

然后我有几个变量:

DECLARE @Answer1 INT
DECLARE @Answer2 INT
....

我需要像这样从表中检索信息:

SET @Answer1 =(SELECT Value FROM AnswerTable WHERE QuestionID=100)
SET @Answer2 =(SELECT Value FROM AnswerTable WHERE QuestionID=101)
...

我想要做的是只从表中选择一个来初始化变量,因为在我的实际情况下,表非常大并且它与其他表连接,我担心子查询的多次执行不会要高效。

是否有捷径可寻?

4

2 回答 2

5

一般来说;

SELECT @Answer1 = col1, @Answer2 = col2, ... FROM yourTable

在你的情况下;

SELECT @Answer1 = case QuestionID when 100 then Value Else @Answer1 End, 
       @Answer2 = case QuestionID when 101 then Value Else @Answer2 End
FROM AnswerTable
WHERE QuestionID IN  (100,101)

例如: Sql Fiddle 示例

于 2012-12-19T12:52:29.727 回答
0

这有点尴尬,但您可以使用连接来执行此操作。

http://sqlfiddle.com/#!3/e3fe7/4

DECLARE @Answer1 INT
DECLARE @Answer2 INT

SELECT 
  @Answer1 = Question100.Value, 
  @Answer2 = Question101.Value 
FROM 
  AnswerTable AS Question100 
INNER JOIN AnswerTable AS Question101 
  ON Question101.QuestionId = 101 
WHERE Question100.QuestionID=100


select @Answer1, @Answer2
于 2012-12-19T12:54:19.390 回答