我想在一个表中插入行。当我开始时,表是空的。我的查询如下。
Select TOP 1 *
INTO #Result
FROM #SmallTable
WHERE CategoryID=11
ORDER BY ExpValue DESC;
它的工作是完美的。但我现在想考虑到this返回无值的情况。但我不知道该如何处理这个问题。
我可以做一个案例,然后选择并询问是否有以下情况 SELECT TOP 1
返回任何值。或者我可以在插入后检查是否有值存在。但哪种方法更好呢?或者还有更好的方法吗?
如果第一次查询没有返回任何记录,你可以在这里使用联合技巧插入一个虚值。
INSERT INTO #Result (col)
SELECT TOP 1 col
FROM
(
SELECT TOP 1 col, 1 AS pos FROM #SmallTable WHERE CategoryID = 11 ORDER BY ExpValue DESC
UNION ALL
SELECT 'NA', 2
) t
ORDER BY pos;
你可以使用 apply
:
select top (1) coalesce(st.CategoryID, 0) as CategoryID, . .
into #destination
from ( values (11)
) t(CategoryID) left join
#SmallTable st
on st.CategoryID = t.CategoryID
order by st.ExpValue desc;