SQL if no rows are returned do this

2019-06-21 22:49发布

I have a select statement and I want to say if this select statement does not return any rows then put a '' in every cell. How do I do this?

7条回答
时光不老,我们不散
2楼-- · 2019-06-21 23:10

It sounds like you're still not getting all the rows you want. True? I think @Joe Sefanelli provides an important part to your solution, and then mentions that you need to change INNER to LEFT joins.

So, you say you want to display all units in your units list. And, if there's no data for a unit, then display the unit and blanks for the data that doesn't exist.

Here's a possible solution. Change your FROM clause to the following:

FROM  [dbo].[Unit] u 
LEFT OUTER JOIN 
    (
    SELECT *
    FROM [dbo].[IUA] i
    JOIN [dbo].[Reports] r ON r.[Report_ID] = i.[Report_ID]
    JOIN [dbo].[State] s ON i.[St_ID] = s.[St_Id]
    WHERE r.[Account] = [dbo].[fn_Get_PortalUser_AccountNumber](11-11)
        AND r.[Rpt_Period] = '2126'
        AND r.[RptName] = 'tfd'
        AND r.[Type] = 'h'    
    ) ir ON ir.[Unit_ID] = u.[Unit_ID]
LEFT JOIN [dbo].[UnitType] ut ON u.[UnitType] = ut.[UnitType]
WHERE u.[Unit] IN (SELECT [VALUE] 
               FROM dbo.udf_GenerateVarcharTableFromStringList(@Units, ','))
;

With this change you will get a list of units that are in the @Units list. The left outer joins will include data associated with each unit, but will not exclude units if there is no associated data.

查看更多
Bombasti
3楼-- · 2019-06-21 23:12
select a, b, c from t
if @@rowcount = 0
    select '' as a, '' as b, '' as c

But make sure you understand that '' may have a different datatype than columns a, b, and c.

查看更多
Deceive 欺骗
4楼-- · 2019-06-21 23:22

Put your blank row select at the bottom of a union

select x.JobName , x.Description
from MasterJobList x
where x.IsCycleJob = 1 

union all

select "" , "" 
from MasterJobList x
where not exists
    (
    select 1
    from MasterJobList x
    where x.IsCycleJob = 1 
    )
查看更多
Viruses.
5楼-- · 2019-06-21 23:24

Based on the posted code, I think you're looking to blank out the columns from the UnitType table as that's the only one you're left-joining to. In that case use

ISNULL(ut.[Description], '')  AS UnitType
查看更多
不美不萌又怎样
6楼-- · 2019-06-21 23:26
select top 1 isnull(max(col2),' ') as noNullCol from table1 where col1='x'

max returns a null where not have rows then isnull function returns ' ' instead a null value

查看更多
该账号已被封号
7楼-- · 2019-06-21 23:30

Try this -

IF NOT EXISTS ( SELECT 'x' FROM <TABLE> .... )
BEGIN
    -- Your logic goes here
END
查看更多
登录 后发表回答