选择不存在的其他空行

时间:2012-10-10 08:34:37

标签: sql sql-server

  

可能重复:
  Include a blank row in query results

我想在SQL查询的最顶层为我的结果集添加一个空行。

我使用的查询是:

SELECT 
    PROFILETITLE, DOCID 
FROM
    PROFILES
WHERE 
    COMPANYCODE = ? 
ORDER BY 
    PROFILETITLE

5 个答案:

答案 0 :(得分:9)

尝试使用union all

SELECT null as PROFILETITLE, null as DOCID 
UNION ALL
SELECT PROFILETITLE, DOCID 
FROM PROFILES
WHERE COMPANYCODE=? 
ORDER BY PROFILETITLE

但如果你不想添加标题,如果DOCIDint类型,则必须使用union allcast,如下所示

SELECT 'PROFILETITLE' as PROFILETITLE, 'DOCID' as DOCID 
UNION ALL
SELECT PROFILETITLE, CAST ( DOCID AS varchar(30) )
FROM PROFILES
WHERE COMPANYCODE=? 
ORDER BY PROFILETITLE

答案 1 :(得分:4)

试试这个:

SELECT '' AS PROFILETITLE, 0 AS DOCID
UNION ALL
SELECT PROFILETITLE, DOCID
FROM PROFILES WHERE COMPANYCODE = ? 
ORDER BY PROFILETITLE

请注意,在使用UNION和所有其他设置操作时,列必须在类型中匹配,因此您必须使用PROFILETITLEDOCID将前两个空值设为别名。而且你必须注意两列的类型以及匹配才能正常工作。您可能需要选择NULL而不是''0

答案 2 :(得分:3)

如果所有列都为varchar,则可以添加“空行”,以这种方式为空,表示''

SELECT PROFILETITLE, DOCID 
FROM PROFILES
WHERE ...

UNION ALL

SELECT '' AS PROFILETITLE, '' AS DOCID

ORDER BY 
  CASE WHEN PROFILETITLE='' AND DOCID='' THEN 0 ELSE 1 END ASC
, PROFILETITLE ASC

答案 3 :(得分:0)

您可以使用SQL Union

SELECT PROFILETITLE, DOCID 
FROM PROFILES
WHERE COMPANYCODE=? ORDER BY PROFILETITLE
UNION ALL
SELECT 0, '' 
FROM SYSIBM.SYSDUMMY1

您可以将SYSIBM.SYSDUMMY1替换为临时表

答案 4 :(得分:0)

工会全部都可以胜任

SELECT 
'' as PROFILETITLE,
'' as DOCID
UNION ALL
SELECT PROFILETITLE, DOCID 
FROM PROFILES
WHERE COMPANYCODE=? ORDER BY PROFILETITLE