在SELECT之前检查列值是否存在

时间:2017-01-04 14:37:13

标签: sql

我有以下SQL语句:

SqlCommand myCmd = new SqlCommand("select distinct(year(date_created)) as theYear from content where folder_id = 1 or folder_id = 2 order by theYear desc", myConn);

此语句检查文件夹中的任何内容,然后将下拉列表设置为等于年份。但是,如果这些文件夹中没有任何内容,则该语句会弹出。这显然发生在每个新的一年还没有创建内容。简单的答案是仅创建一个内容,以解决问题。我想确保它的设置,以便在出现问题时没有人担心它。那么,有没有办法在尝试选择之前检查该列中是否有值。

我尝试了以下内容:

SELECT DISTINCT (ISNULL(year(date_created), year(getdate()))) AS theYear
FROM content
WHERE folder_id = 1
    OR folder_id = 2
ORDER BY theYear DESC

似乎没有用。我也尝试了COUNT,但是我的语法错误或者我使用不正确。

任何人都可以让我知道我哪里出错了,方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用UNION来确定当前年份的数据集。由于UNION删除了重复项,因此Content

中已存在重复项无关紧要
SELECT  YEAR(date_created) AS theYear
FROM    Content
WHERE   folder_id IN (1, 2)
UNION
SELECT  YEAR(GETDATE())
ORDER BY theYear DESC;

如果您只想在没有数据的情况下显示当前年份,那么您可以在第二个查询中输入并EXISTS

SELECT  YEAR(date_created) AS theYear
FROM    Content
WHERE   folder_id IN (1, 2)
UNION
SELECT  YEAR(GETDATE())
WHERE   NOT EXISTS (SELECT 1 FROM Content WHERE folder_id IN (1, 2) )
ORDER BY theYear DESC;

答案 1 :(得分:0)

您更新的语句仍将应用where子句,以防止返回任何记录,NULL或其他。

select distinct
    (ISNULL(year(date_created), year(getdate()))) as theYear
from content
where folder_id = 1
    or folder_id = 2
order by theYear desc

尝试将其更改为

DECLARE @yearTbl TABLE 
(
    date_created DATE
)

INSERT @yearTbl
SELECT date_created
FROM content
WHERE folder_id = 1
    OR folder_id = 2

IF (SELECT count(*) FROM @yearTbl) = 0
    SELECT year(getdate()) AS theYear
ELSE
    SELECT DISTINCT year(date_created) AS theYear
    FROM @yearTbl
    ORDER BY theYear