我试图检查一个值是否存在;问题是我不想为速度问题运行两次查询。有没有人知道如何获得此查询的结果而不运行它两次?见下面的例子。
if exists(select [row1],[row2] from [tablename] where [row2] = 'myvariable')
BEGIN
PRINT 'EXISTS'
// -- GET VALUE OF ROW 2 without running another query
END
ELSE
BEGIN
PRINT 'DOES NOT EXIST'
END
答案 0 :(得分:3)
一种可能性:使用临时表。
SELECT [row1]
, [row2]
INTO #tmp
FROM [tablename]
WHERE [row2] = 'myvariable'
IF EXISTS ( SELECT *
FROM #tmp )
BEGIN
PRINT 'EXISTS'
SELECT row2
FROM #tmp t
END
ELSE
BEGIN
PRINT 'DOES NOT EXIST'
END
答案 1 :(得分:0)
为了提高速度,并避免两次查询相同的数据,请尝试此操作。它只返回逻辑检查中的一行,您不必从表中提取数据。在这种情况下,我在列[row2] ='myvariable'
时返回'what' if exists(select top 1 'whatever' from [tablename] where [row2] = 'myvariable')
BEGIN
PRINT 'EXISTS'
// -- GET VALUE OF ROW 2 without running another query
END
ELSE
BEGIN
PRINT 'DOES NOT EXIST'
END