Showing posts with label null. Show all posts
Showing posts with label null. Show all posts

Tuesday, March 27, 2012

Case Statement

Hi!

I need a case that returns the result of a select if it is not null, and -1 if it is null. I did it this way:

select

case

when(select column from table where conditions) is null then -1

else(select column from table where conditions)

But it doesn't seem very clever to repeat the select statement. Is there any way I can do it without repeating the "select column from table where conditions"?

Thank you!

Try this:

select column = case column
when null then -1
else column
end
from table
where conditions

|||

You can write it like below which is ANSI SQL syntax:

select coalesce(column , -1) as column from table

COALESCE is just a short-hand for a special form of CASE expression like:

case when expr1 is not null then expr1

when expr2 is not null then expr2

...

end

Another proprietary TSQL method is to use isnull function:

select isnull(column, -1) as column from table

|||

Try either of

select coalesce(col, -1) from tab
go

select isnull(col, -1) from tab
go

Unfortunately, Allen's suggestion doesn't work because the "null" appearing in the when_expression causes it to always evaluate to false.

|||

Now it seems clever! :)

Thank you!!!

|||

Allen was almost there.

If you change this example slightly:

select column = case column
when null then -1
else column
end
from table
where conditions

to this..

select column = case
when column is null then -1
else column
end
from table
where conditions

..it'll work as expected

=;o)
/Kenneth

CASE Statement

Hello,
I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
Denied or NULL). On my web page, I have a dropdown box which the user can
select 3 items (Approved, Denied or Pending). When they choose "Pending",
I want to retrieve the fields that are NULL. I've tried the following WHERE
statement, but I can't capture the NULL fields.
@.strParm03 can equal "All, Approved, Denied or NULL)
WHERE
ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
WHEN 'Pending' THEN NULL
ELSE @.strParm03 END
Any help with this would be appreciated.
--
Thanks in advance,
sck10I would use a script like:
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and ApprovalStatus is null)
[/code]
or
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and isnull(ApprovalStatus,'') ='')
[/code]
HTH,
Cristian Lefter, SQL Server MVP
"sck10" <sck10@.online.nospam> wrote in message
news:Oafy0raXFHA.3032@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
> Denied or NULL). On my web page, I have a dropdown box which the user can
> select 3 items (Approved, Denied or Pending). When they choose
> "Pending",
> I want to retrieve the fields that are NULL. I've tried the following
> WHERE
> statement, but I can't capture the NULL fields.
> @.strParm03 can equal "All, Approved, Denied or NULL)
> WHERE
> ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
> WHEN 'Pending' THEN NULL
> ELSE @.strParm03 END
> Any help with this would be appreciated.
> --
> Thanks in advance,
> sck10
>

CASE Statement

Hello,
I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
Denied or NULL). On my web page, I have a dropdown box which the user can
select 3 items (Approved, Denied or Pending). When they choose "Pending",
I want to retrieve the fields that are NULL. I've tried the following WHERE
statement, but I can't capture the NULL fields.
@.strParm03 can equal "All, Approved, Denied or NULL)
WHERE
ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
WHEN 'Pending' THEN NULL
ELSE @.strParm03 END
Any help with this would be appreciated.
Thanks in advance,
sck10
I would use a script like:
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and ApprovalStatus is null)
[/code]
or
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and isnull(ApprovalStatus,'') ='')
[/code]
HTH,
Cristian Lefter, SQL Server MVP
"sck10" <sck10@.online.nospam> wrote in message
news:Oafy0raXFHA.3032@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
> Denied or NULL). On my web page, I have a dropdown box which the user can
> select 3 items (Approved, Denied or Pending). When they choose
> "Pending",
> I want to retrieve the fields that are NULL. I've tried the following
> WHERE
> statement, but I can't capture the NULL fields.
> @.strParm03 can equal "All, Approved, Denied or NULL)
> WHERE
> ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
> WHEN 'Pending' THEN NULL
> ELSE @.strParm03 END
> Any help with this would be appreciated.
> --
> Thanks in advance,
> sck10
>

CASE Statement

Hello,
I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
Denied or NULL). On my web page, I have a dropdown box which the user can
select 3 items (Approved, Denied or Pending). When they choose "Pending",
I want to retrieve the fields that are NULL. I've tried the following WHERE
statement, but I can't capture the NULL fields.
@.strParm03 can equal "All, Approved, Denied or NULL)
WHERE
ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
WHEN 'Pending' THEN NULL
ELSE @.strParm03 END
Any help with this would be appreciated.
--
Thanks in advance,
sck10I would use a script like:
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and ApprovalStatus is null)
[/code]
or
[code]
where @.strParm03 = 'All'
or (@.strParm03='Approved' and ApprovalStatus='Approved')
or (@.strParm03='Denied' and ApprovalStatus='Denied')
or (@.strParm03='Pending' and isnull(ApprovalStatus,'') ='')
[/code]
HTH,
Cristian Lefter, SQL Server MVP
"sck10" <sck10@.online.nospam> wrote in message
news:Oafy0raXFHA.3032@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I have a varchar field (ApprovalStatus) that can have 3 results (Approved,
> Denied or NULL). On my web page, I have a dropdown box which the user can
> select 3 items (Approved, Denied or Pending). When they choose
> "Pending",
> I want to retrieve the fields that are NULL. I've tried the following
> WHERE
> statement, but I can't capture the NULL fields.
> @.strParm03 can equal "All, Approved, Denied or NULL)
> WHERE
> ApprovalStatus LIKE CASE @.strParm03 WHEN 'all' THEN '%'
> WHEN 'Pending' THEN NULL
> ELSE @.strParm03 END
> Any help with this would be appreciated.
> --
> Thanks in advance,
> sck10
>

Thursday, March 22, 2012

CASE Returning NULL

Hello,

I have a query that contains six derived columns;

FirstPerYr; The current year
FirstPerMo; The current month
FirstPeriodRevenue; CASE the current year, use the CurrentYearSalesTable (CY). CASE the current month, match the correct column (JanRev, FebRev, etc) of the CurrentYearSalesTable to get the correct data.
FirstPeriodYrAnnum; Last year
FirstPeriodMoAnnum; The current month, last year
FirstPeriodAnnumRev; Same as FirstPeriodRevenue, but from the year and month before.

In the following query, I get the correct FirstPeriodRev value, but FirstPeriodAnnumRev comes up NULL. I know I have data for January 2006. The query is as follows;

--**************************

DECLARE @.FirstPerYr Int
DECLARE @.FirstPerMo Int
DECLARE @.FirstPerYrAnnum Int
DECLARE @.FirstPerMoAnnum Int

SET @.FirstPerYr = YEAR(GETDATE())
SET @.FirstPerMo = MONTH(GETDATE())
SET @.FirstPerYrAnnum = YEAR(DateAdd(Year,-1,DateAdd(Month,0,GetDate())))
SET @.FirstPerMoAnnum = MONTH(DateAdd(Year,-1,DateAdd(Month,0,GetDate())))


SELECT
RTRIM(DA.AcctCode) AS DAAcctCode,
RTRIM(DA.CompanyName) AS DACompanyName,
@.FirstPerYr AS FirstPerYr,
@.FirstPerMo AS FirstPerMo,
"FirstPeriodRev" =
CASE
WHEN @.FirstPerYr = DATEPART(YEAR,GETDATE()) THEN
CASE
WHEN @.FirstPerMo = 1 THEN SUM(CY.JanRev)
WHEN @.FirstPerMo = 2 THEN SUM(CY.FebRev)
WHEN @.FirstPerMo = 3 THEN SUM(CY.MarRev)
WHEN @.FirstPerMo = 4 THEN SUM(CY.AprRev)
WHEN @.FirstPerMo = 5 THEN SUM(CY.MayRev)
WHEN @.FirstPerMo = 6 THEN SUM(CY.JunRev)
WHEN @.FirstPerMo = 7 THEN SUM(CY.JulRev)
WHEN @.FirstPerMo = 8 THEN SUM(CY.AugRev)
WHEN @.FirstPerMo = 9 THEN SUM(CY.SeptRev)
WHEN @.FirstPerMo = 10 THEN SUM(CY.OctRev)
WHEN @.FirstPerMo = 11 THEN SUM(CY.NovRev)
WHEN @.FirstPerMo = 12 THEN SUM(CY.DecRev)
END
END,
@.FirstPerYrAnnum AS FirstPerYrAnnum,
@.FirstPerMoAnnum AS FirstPerMoAnnum,
"FirstPeriodAnnumRev" =
CASE
WHEN @.FirstPerYrAnnum = DATEADD(YEAR,-1,GETDATE()) THEN
CASE
WHEN @.FirstPerMoAnnum = 1 THEN SUM(PY.JanRev)
WHEN @.FirstPerMoAnnum = 2 THEN SUM(PY.FebRev)
WHEN @.FirstPerMoAnnum = 3 THEN SUM(PY.MarRev)
WHEN @.FirstPerMoAnnum = 4 THEN SUM(PY.AprRev)
WHEN @.FirstPerMoAnnum = 5 THEN SUM(PY.MayRev)
WHEN @.FirstPerMoAnnum = 6 THEN SUM(PY.JunRev)
WHEN @.FirstPerMoAnnum = 7 THEN SUM(PY.JulRev)
WHEN @.FirstPerMoAnnum = 8 THEN SUM(PY.AugRev)
WHEN @.FirstPerMoAnnum = 9 THEN SUM(PY.SeptRev)
WHEN @.FirstPerMoAnnum = 10 THEN SUM(PY.OctRev)
WHEN @.FirstPerMoAnnum = 11 THEN SUM(PY.NovRev)
WHEN @.FirstPerMoAnnum = 12 THEN SUM(PY.DecRev)
END
END
FROM

SalesCommissions.dbo.DailyAccountsDownload DA
INNER JOIN (SELECT
AcctCode,
Territory,
SUM(JanRev) AS JanRev,
SUM(FebRev) AS FebRev,
SUM(MarRev) AS MarRev,
SUM(AprRev) AS AprRev,
SUM(MayRev) AS MayRev,
SUM(JunRev) AS JunRev,
SUM(JulRev) AS JulRev,
SUM(AugRev) AS AugRev,
SUM(SeptRev) AS SeptRev,
SUM(OctRev) AS OctRev,
SUM(NovRev) AS NovRev,
SUM(DecRev) AS DecRev
FROM
SalesReporting.dbo.PriorYearSales
GROUP BY
AcctCode, Territory)PY
ON RTRIM(DA.AcctCode) = RTRIM(PY.AcctCode)
INNER JOIN (SELECT
AcctCode,
SUM(JanRev) AS JanRev,
SUM(FebRev) AS FebRev,
SUM(MarRev) AS MarRev,
SUM(AprRev) AS AprRev,
SUM(MayRev) AS MayRev,
SUM(JunRev) AS JunRev,
SUM(JulRev) AS JulRev,
SUM(AugRev) AS AugRev,
SUM(SeptRev) AS SeptRev,
SUM(OctRev) AS OctRev,
SUM(NovRev) AS NovRev,
SUM(DecRev) AS DecRev
FROM
SalesReporting.dbo.CurrentYearSales
GROUP BY
AcctCode)CY
ON RTRIM(DA.AcctCode) = RTRIM(CY.AcctCode)
WHERE
RTRIM(DA.AcctCode) = 'AM940'

GROUP BY
RTRIM(DA.AcctCode), DA.CompanyName

--*************************

The result set looks like this;

DAAcctCode DACompanyName FirstPerYr FirstPerMo FirstPeriodRev FirstPerYrAnnum FirstPerMoAnnum FirstPeriodAnnumRev
AM940 Sterling Educationa 2007 1 1769.75 2006 1 NULL

If the logic for CASE is the same to find the correct column for the previous year, then why would the result for the previous year come up NULL?

Thanks again for your help!

CSDunn

here ur doin a SUM in case statement...if ne of the data whose sum is being taken is null..it'll show the result as null...guess thats wats hapennin...check the data...|||

Thank you for your response. I tried to just set the True condition of the first WHEN to zero, and still got NULL. Then I tried to edit the exiting True condition from SUM(PY.JanRev) to SUM(ISNULL(PY.JanRev,0)) and still got NULL.

cdun2

|||

I found the problem. When evaluating @.FirstPerYrAnnum = DATEADD(YEAR,-1,GETDATE())), The variable @.FirstPerYrAnnum contained only the YEAR portion of the date. I needed to express my test as follows;

@.FirstPerYrAnnum = YEAR(DATEADD(YEAR,-1,GETDATE()))

Now I get back something that looks correct. I need to test.

Putting an ELSE condition in the outer CASE helped me find this.

Thank you again for your help!

CSDunn

|||put an else in both inner and outer case...see if it goes there...|||

o..u already got it...:)...

always use an else in case statements..gud practice..u nvr know when u need it..

CASE problem (or is it a null problem?)

I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
--
Andrew C. Madsen
Information Architect
Harley-Davidson Motor CompanyFirst, you should be using IS NULL. Second, you should have an ELSE in each
of those CASE's. Otherwise, the default is NULL. However, this can be done
without CASE's. Looks like you may want:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT
ISNULL (TIN, 'Dummy')
, ISNULL (PSTATE, 'Dummy')
, ISNULL (PCITY, 'Dummy')
, PNAME1
, PADDR
FROM dbo.EXPTRANS
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
--
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company|||More correct is
Case WHEN TIN IS NULL THEN 'Dummy' ELSE TIN END
Bojidar Alexandrov|||Thank you all
--
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
> I have this insert statement:
> INSERT INTO dbo.TinNormalized
> (TIN, PState, PCity, PName1, PAddr)
> SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
> Case When PSTATE = NULL Then 'Dummy' END,
> Case When PCITY = Null Then 'Dummy' END,
> PNAME1, PADDR
> FROM dbo.EXPTRANS
> it fails with this message:
> Cannot insert the value NULL into column 'TIN', table
> 'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
> The statement has been terminated.
> I have tried it with IS NULL as well and yet I get the same error. What am
I
> missing?
> --
> Andrew C. Madsen
> Information Architect
> Harley-Davidson Motor Company
>

CASE problem (or is it a null problem?)

I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company
First, you should be using IS NULL. Second, you should have an ELSE in each
of those CASE's. Otherwise, the default is NULL. However, this can be done
without CASE's. Looks like you may want:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT
ISNULL (TIN, 'Dummy')
, ISNULL (PSTATE, 'Dummy')
, ISNULL (PCITY, 'Dummy')
, PNAME1
, PADDR
FROM dbo.EXPTRANS
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company
|||More correct is
Case WHEN TIN IS NULL THEN 'Dummy' ELSE TIN END
Bojidar Alexandrov
|||Thank you all
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
> I have this insert statement:
> INSERT INTO dbo.TinNormalized
> (TIN, PState, PCity, PName1, PAddr)
> SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
> Case When PSTATE = NULL Then 'Dummy' END,
> Case When PCITY = Null Then 'Dummy' END,
> PNAME1, PADDR
> FROM dbo.EXPTRANS
> it fails with this message:
> Cannot insert the value NULL into column 'TIN', table
> 'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
> The statement has been terminated.
> I have tried it with IS NULL as well and yet I get the same error. What am
I
> missing?
> --
> Andrew C. Madsen
> Information Architect
> Harley-Davidson Motor Company
>
sql

CASE problem (or is it a null problem?)

I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
Andrew C. Madsen
Information Architect
Harley-Davidson Motor CompanyFirst, you should be using IS NULL. Second, you should have an ELSE in each
of those CASE's. Otherwise, the default is NULL. However, this can be done
without CASE's. Looks like you may want:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT
ISNULL (TIN, 'Dummy')
, ISNULL (PSTATE, 'Dummy')
, ISNULL (PCITY, 'Dummy')
, PNAME1
, PADDR
FROM dbo.EXPTRANS
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
I have this insert statement:
INSERT INTO dbo.TinNormalized
(TIN, PState, PCity, PName1, PAddr)
SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
Case When PSTATE = NULL Then 'Dummy' END,
Case When PCITY = Null Then 'Dummy' END,
PNAME1, PADDR
FROM dbo.EXPTRANS
it fails with this message:
Cannot insert the value NULL into column 'TIN', table
'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I have tried it with IS NULL as well and yet I get the same error. What am I
missing?
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company|||More correct is
Case WHEN TIN IS NULL THEN 'Dummy' ELSE TIN END
Bojidar Alexandrov|||Thank you all
Andrew C. Madsen
Information Architect
Harley-Davidson Motor Company
"Andrew Madsen" <andrew.madsen@.harley-davidson.com> wrote in message
news:OpRcUtuLEHA.628@.TK2MSFTNGP11.phx.gbl...
> I have this insert statement:
> INSERT INTO dbo.TinNormalized
> (TIN, PState, PCity, PName1, PAddr)
> SELECT DISTINCT Case WHEN TIN = NULL THEN 'Dummy' END,
> Case When PSTATE = NULL Then 'Dummy' END,
> Case When PCITY = Null Then 'Dummy' END,
> PNAME1, PADDR
> FROM dbo.EXPTRANS
> it fails with this message:
> Cannot insert the value NULL into column 'TIN', table
> 'CNATEST.dbo.TinNormalized'; column does not allow nulls. INSERT fails.
> The statement has been terminated.
> I have tried it with IS NULL as well and yet I get the same error. What am
I
> missing?
> --
> Andrew C. Madsen
> Information Architect
> Harley-Davidson Motor Company
>

Case null

CASE(@.CustomText) WHEN NULL THEN 'Status changed to ' +
@.StatusDescription
ELSE @.CustomText + ' ' +
@.StatusDescription END
Now, @.CustomText is either null or has value. WHEN NULL does not work. How
do i get it to work?Already replied to other post.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Justin" <jus820@.hotmail.com> wrote in message news:evOIVwreGHA.2456@.TK2MSFTNGP04.phx.gbl..
.
> CASE(@.CustomText) WHEN NULL THEN 'Status changed to ' + @.StatusDescri
ption
> ELSE @.CustomText + ' ' + @.StatusDe
scription END
>
> Now, @.CustomText is either null or has value. WHEN NULL does not work. H
ow do i get it to work?
>|||CASE WHEN @.CustomText IS NULL THEN ... END
or just use COALESCE
COALESCE(@.CustomText + ' ' + @.StatusDescription, @.StatusDescription)
"Justin" <jus820@.hotmail.com> wrote in message
news:evOIVwreGHA.2456@.TK2MSFTNGP04.phx.gbl...
> CASE(@.CustomText) WHEN NULL THEN 'Status changed to ' +
> @.StatusDescription
> ELSE @.CustomText + ' ' +
> @.StatusDescription END
>
> Now, @.CustomText is either null or has value. WHEN NULL does not work.
> How do i get it to work?
>

case null

how do you deal with case null?
CASE @.test WHEN NULL THEN .........[columnname] =
CASE
WHEN [columnname] IS NULL THEN 'It's NULL'
ELSE 'It's not NULL'
END|||The expression implies:
CASE WHEN @.test = NULL THEN...
And you probably know value = NULL evaluates to UNKNOWN which in turn (in mo
st cases) evaluates to
FALSE. Here's how to do:
CASE WHEN @.test IS NULL THEN...
So, use a searched case instead of a simple case.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Justin" <jus820@.hotmail.com> wrote in message news:%23EpRzureGHA.4828@.TK2MSFTNGP05.phx.gbl
..
> how do you deal with case null?
> CASE @.test WHEN NULL THEN .........
>|||CASE
WHEN @.test IS NULL THEN...
HTH
Vern
"Justin" wrote:

> how do you deal with case null?
> CASE @.test WHEN NULL THEN .........
>
>|||for future reference...
null is not a value. and it's a grave mistake to use it as such in the
database. try to avoid inserting null in the database at all cost;
certain cases are unavoidable, however.
since it's not a value, you can't compare against it. ie. x = null.sql

CASE JOIN question

I woul like to join table with other table only in case when @.myParam is
null.
Example:
something like that:
...table1 T1
case when @.myParam is null then
INNER JOIN table2 T2 ON T1.zone=T2.zone
else end
.....
Is that possible?
Thnk you,
Simonsimon
Use pubs
SELECT a.au_lname, a.au_fname, a.address,
t.title, t.type
FROM authors a INNER JOIN
titleauthor ta ON ta.au_id = a.au_id INNER JOIN
titles t ON t.title_id = ta.title_id
INNER JOIN publishers p on t.pub_id =
CASE WHEN t.type = 'Business' THEN p.pub_id ELSE null END
INNER JOIN stores s on s.stor_id =
CASE WHEN t.type = 'Popular_comp' THEN t.title_id ELSE null END
"simon" <simon.zupan@.stud-moderna.si> wrote in message
news:OwhFXArOFHA.1476@.TK2MSFTNGP09.phx.gbl...
> I woul like to join table with other table only in case when @.myParam is
> null.
> Example:
> something like that:
> ...table1 T1
> case when @.myParam is null then
> INNER JOIN table2 T2 ON T1.zone=T2.zone
> else end
> .....
> Is that possible?
> Thnk you,
> Simon
>|||Hi Uri,
thank you for your answer.
I have little different example ( also instead of "=" I have like) .
If myParam is not null, my table2 is empty.
So inner join:
table1 T1 INNER JOIN table2 T2 ON T1.zone like
CASE when @.myParam is null then T2.zone else NULL END
will not work correctly.
I tried like this:
table1 T1 INNER JOIN table2 T2 ON 1=
(CASE when @.myParam is not null then 1 else case when T1.zone like
'%'+T2.zone+'%' then 1 else 0 end end )
It works but it's too slow.
Any idea?
Regards,
Simon
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:e3FBGDrOFHA.244@.TK2MSFTNGP12.phx.gbl...
> simon
> Use pubs
> SELECT a.au_lname, a.au_fname, a.address,
> t.title, t.type
> FROM authors a INNER JOIN
> titleauthor ta ON ta.au_id = a.au_id INNER JOIN
> titles t ON t.title_id = ta.title_id
> INNER JOIN publishers p on t.pub_id =
> CASE WHEN t.type = 'Business' THEN p.pub_id ELSE null END
> INNER JOIN stores s on s.stor_id =
> CASE WHEN t.type = 'Popular_comp' THEN t.title_id ELSE null END
>
> "simon" <simon.zupan@.stud-moderna.si> wrote in message
> news:OwhFXArOFHA.1476@.TK2MSFTNGP09.phx.gbl...
>|||Simon
Try this one (untested)
table1 T1 INNER JOIN table2 T2 ON 1=
CASE
WHEN EXISTS (
SELECT * FROM Table2
WHERE T1.zone like '%'+T2.zone+'%')
THEN 1
ELSE 0
END
"simon" <simon.zupan@.stud-moderna.si> wrote in message
news:%23xd$3RrOFHA.2144@.TK2MSFTNGP09.phx.gbl...
> Hi Uri,
> thank you for your answer.
> I have little different example ( also instead of "=" I have like) .
> If myParam is not null, my table2 is empty.
> So inner join:
> table1 T1 INNER JOIN table2 T2 ON T1.zone like
> CASE when @.myParam is null then T2.zone else NULL END
> will not work correctly.
> I tried like this:
> table1 T1 INNER JOIN table2 T2 ON 1=
> (CASE when @.myParam is not null then 1 else case when T1.zone like
> '%'+T2.zone+'%' then 1 else 0 end end )
> It works but it's too slow.
> Any idea?
> Regards,
> Simon
>
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:e3FBGDrOFHA.244@.TK2MSFTNGP12.phx.gbl...
is
>

Tuesday, March 20, 2012

Case in Join

Can you put a Case statement in a Join?
My problem is that I have 2 possible fields I want to join to the same
table. If one is null, use the other.
For example:
Create Table Position
(
UserID1 int,
UserID2 int
)
Create Table Logon
(
UserID int,
UserName
)
I want to do something like (I know this doesn't work, but you should get
the idea of what I am looking for from it).
Select UserName From Position P Join on Logon L (CASE WHEN UserID1 is not
null Then (P.UserID1 = L.UserID) ELSE (P.UserID2 = L.UserID) END)
I am trying to get the User Name from UserID1, unless it is null. If that
is the case, then get the User Name from UserID2.
Thanks,
TomSelect UserName From Position P Join Logon L
-- the join condition implies that UserID1 is not null
on P.UserID1 = L.UserID
union all
Select UserName From Position P Join on Logon L on P.UserID2 = L.UserID
where UserID1 is null|||The case statement will work, but the isnull function is better.
select isnull(columnA, columnB).
If you have multiple columns to compare for nulls use coalesce. select
coalesce(columnA,columnB,columnC...)|||"Gary Gibbs" <ggibbs@.aahs.org> wrote in message
news:1135974528.225930.160070@.g44g2000cwa.googlegroups.com...
> The case statement will work, but the isnull function is better.
> select isnull(columnA, columnB).
I tried to use the Case statement, but got an error on the "=" sign.

> If you have multiple columns to compare for nulls use coalesce. select
> coalesce(columnA,columnB,columnC...)
I don't see how the isnull or coalesce.helps me. If I were looking for the
IsNull from the data that would be fine, but in my case I have 2 UserID,
which would be different records in the Logon table. I need to use a Join
to get the correct UserName, I believe. Using the isnull would get me the
correct UserID, but I still don't have the User Name for that UserID.
Perhaps 2 separate joins.
Thanks,
Tom|||tshad wrote:

> Can you put a Case statement in a Join?
Of course...

> Create Table Position
> (
> UserID1 int,
> UserID2 int
> )
> Create Table Logon
> (
> UserID int,
> UserName
> )
> I want to do something like (I know this doesn't work, but you should get
> the idea of what I am looking for from it).
> Select UserName From Position P Join on Logon L (CASE WHEN UserID1 is not
> null Then (P.UserID1 = L.UserID) ELSE (P.UserID2 = L.UserID) END)
Select UserName
From Position P Join Logon L
on coalesce(P.UserID1, P.UserID2) = L.UserID
Dieter|||Using Case:
Select UserName From Position P Join Logon L On L.UserId = Case When
P.UserId1 Is Not Null Then P.UserId1 Else P.UserId2 End
Using Coalesce:
Select UserName From Position P Join Logon L On L.UserId =
Coalesce(P.UserId1, P.UserId2)
Using Isnull:
Select UserName From Position P Join Logon L On L.UserId =
Isnull(P.Userid1, P.UserId2)
tshad wrote:
> Can you put a Case statement in a Join?
> My problem is that I have 2 possible fields I want to join to the same
> table. If one is null, use the other.
> For example:
> Create Table Position
> (
> UserID1 int,
> UserID2 int
> )
> Create Table Logon
> (
> UserID int,
> UserName
> )
> I want to do something like (I know this doesn't work, but you should get
> the idea of what I am looking for from it).
> Select UserName From Position P Join on Logon L (CASE WHEN UserID1 is not
> null Then (P.UserID1 = L.UserID) ELSE (P.UserID2 = L.UserID) END)
> I am trying to get the User Name from UserID1, unless it is null. If that
> is the case, then get the User Name from UserID2.
> Thanks,
> Tom
>|||Is performance a concern for you? Are the tables big?|||tshad (tscheiderich@.ftsolutions.com) writes:
> "Gary Gibbs" <ggibbs@.aahs.org> wrote in message
> news:1135974528.225930.160070@.g44g2000cwa.googlegroups.com...
> I tried to use the Case statement, but got an error on the "=" sign.
CASE is not a statement in T-SQL, it is an expression. And just like
any other expression it returns a value. Thus what you had:
Select UserName
From Position P
Join on Logon L (CASE WHEN UserID1 is not null
Then (P.UserID1 = L.UserID)
ELSE (P.UserID2 = L.UserID)
END)
Does not cut it, because
1) ON appears to eaarly, it should come after the table with its alias.
2) The JOIN operator is followed by a boolean expression, but CASE
can never return boolean, because there is no boolean datatype in
SQL.
3) And therefore the value of one branch in the CASE cannot be
"P.UserID1 = L.UserID".
This you can write:
Select UserName
From Position P
Join Logon L ON L.UserUD = CASE WHEN P.UserID1 is not null
Then P.UserID1
ELSE P.UserID2
END
coalesce(P.UserID1, P.UserID2) is a short-hand notation for the same
thing.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns973CF3D7CD071Yazorman@.127.0.0.1...
> tshad (tscheiderich@.ftsolutions.com) writes:
> CASE is not a statement in T-SQL, it is an expression. And just like
> any other expression it returns a value. Thus what you had:
That makes sense now.

> Select UserName
> From Position P
> Join on Logon L (CASE WHEN UserID1 is not null
> Then (P.UserID1 = L.UserID)
> ELSE (P.UserID2 = L.UserID)
> END)
> Does not cut it, because
> 1) ON appears to eaarly, it should come after the table with its alias.
> 2) The JOIN operator is followed by a boolean expression, but CASE
> can never return boolean, because there is no boolean datatype in
> SQL.
> 3) And therefore the value of one branch in the CASE cannot be
> "P.UserID1 = L.UserID".
> This you can write:
> Select UserName
> From Position P
> Join Logon L ON L.UserUD = CASE WHEN P.UserID1 is not null
> Then P.UserID1
> ELSE P.UserID2
> END
That works great.

> coalesce(P.UserID1, P.UserID2) is a short-hand notation for the same
> thing.
This also would work. I misunderstood what Gary was saying.
Thanks,
Tom

>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx

case in HAVING statement

How can I include case in having statement:
......
HAVING case when @.korak=1440 then (T5.fromTime is not null AND T5.toTime is
not null) else
((T5.fromTime is null AND T5.toTime is null AND T5.izd_nivo is null) OR (T5.
fromTime is not null AND T5.toTime is not null)) end
This isn't working, wrong sintaks. Does anybody know the right sintaks?
Thank you,
SimonCASE is an expression, it returns a scalar value than you can compare with s
omething else, not a Boolean.
And considering that you don't have any aggregates in your HAVING clause, it
makes more sense to make it a WHERE clause. And the clause includes rows th
at have (T5.fromTime is not null AND T5.toTime is not null) anyway, whether
@.korak equals 1440 or not. So the following simplifies version should do the
job:
WHERE (T5.fromTime is not null AND T5.toTime is not null)
OR (@.korak!=1440 AND T5.fromTime is null AND T5.toTime is null AND T5.izd_ni
vo is null)
--
Jacco Schalkwijk
SQL Server MVP
"simon" <simon.zupan@.stud-moderna.si> wrote in message news:erbE0VDNFHA.3668
@.TK2MSFTNGP14.phx.gbl...
How can I include case in having statement:
.....
HAVING case when @.korak=1440 then (T5.fromTime is not null AND T5.toTime is
not null) else
((T5.fromTime is null AND T5.toTime is null AND T5.izd_nivo is null) OR (T5.
fromTime is not null AND T5.toTime is not null)) end
This isn't working, wrong sintaks. Does anybody know the right sintaks?
Thank you,
Simon|||Thank you Jacco. I have aggregates but I didn't write them here. It doesn't
matter.
But what if I have :
...
) as T5 GROUP BY T5.fromtime,T5.totime,t5.izd_nivo WITH ROLLUP
HAVING CASE WHEN @.korak=1440 then (T5.fromTime is null AND T5.toTime is null
AND T5.izd_nivo is null)
else (T5.fromTime is not null AND T5.toTime is not null) end
Regards,
Simon
"Jacco Schalkwijk" <jacco.please.reply@.to.newsgroups.mvps.org.invalid> wrote
in message news:Oz$ay7DNFHA.3380@.TK2MSFTNGP15.phx.gbl...
CASE is an expression, it returns a scalar value than you can compare with s
omething else, not a Boolean.
And considering that you don't have any aggregates in your HAVING clause, it
makes more sense to make it a WHERE clause. And the clause includes rows th
at have (T5.fromTime is not null AND T5.toTime is not null) anyway, whether
@.korak equals 1440 or not. So the following simplifies version- should do th
e job:
WHERE (T5.fromTime is not null AND T5.toTime is not null)
OR (@.korak!=1440 AND T5.fromTime is null AND T5.toTime is null AND T5.izd_ni
vo is null)
--
Jacco Schalkwijk
SQL Server MVP
"simon" <simon.zupan@.stud-moderna.si> wrote in message news:erbE0VDNFHA.3668
@.TK2MSFTNGP14.phx.gbl...
How can I include case in having statement:
......
HAVING case when @.korak=1440 then (T5.fromTime is not null AND T5.toTime is
not null) else
((T5.fromTime is null AND T5.toTime is null AND T5.izd_nivo is null) OR (T5.
fromTime is not null AND T5.toTime is not null)) end
This isn't working, wrong sintaks. Does anybody know the right sintaks?
Thank you,
Simon|||As Jacco suggested, in your example you can use WHERE rather than
HAVING - although the logic is the same in either case:
WHERE (@.korak=1440 AND T5.fromtime IS NULL AND T5.totime IS NULL AND
T5.izd_nivo IS NULL)
OR (@.korak<>1440 AND T5.fromtime IS NOT NULL AND T5.totime IS NOT
NULL)
Try also using UNION, which may give a better execution plan:
SELECT ...
WHERE @.korak=1440
AND T5.fromtime IS NULL
AND T5.totime IS NULL
AND T5.izd_nivo IS NULL
UNION ALL
SELECT ...
WHERE @.korak<>1440
AND T5.fromtime IS NOT NULL
AND T5.totime IS NOT NULL
David Portas
SQL Server MVP
--|||To use CASE in criteria, I use the following:
WHERE (1=Case when [your criteria = true] then 1 else 0 end)
HTH
Fred
"simon" wrote:

> How can I include case in having statement:
> ......
> HAVING case when @.korak=1440 then (T5.fromTime is not null AND T5.toTime i
s not null) else
> ((T5.fromTime is null AND T5.toTime is null AND T5.izd_nivo is null) OR (T
5.fromTime is not null AND T5.toTime is not null)) end
> This isn't working, wrong sintaks. Does anybody know the right sintaks?
> Thank you,
> Simon
>

case expression plus outer join in ole db source

I'm trying to generate the data for a 2-column table, where both columns are defined as NOT NULL and the second column is a uniqueidentifier.

In SQL Server Management Studio, this works fine:

insert into table_3(column_a, column_b)

select table_1.column_a, (case when table_2.column_b is NULL then newid() else table_2.column_b end) as column_b

from table_1 left outer join table_2 on table_1.column_c = table_2.column_c

That is, column_b of the SELECT result has no NULL values, and all 35,986 rows are successfully inserted into a previously empty table_3. (If I comment out the INSERT INTO clause and project table_2.column_b instead of "(case ... end) as column_b", the SELECT result includes 380 rows with a NULL in column_b, so I know the case expression plus the outer join are working as expected.)

But when I use the SELECT query as the SQL command in an OLE DB Source component that is connected directly to the OLE DB Destination for the result table, I get this error:

There was an error with input column "column_b" (445) on input "OLE DB Destination Input" (420

The column status returned was: "The value violated the integrity constraints for the column.".

And sure enough, when I modify the result table to allow NULL in column_b, truncate it, and re-run the data flow, it inserts the exact same 380 rows with a NULL in column_b among the 35,986 rows.

So what is SSIS doing to screw up the results of the SELECT command?

Kevin,

Can you see the values of column_b when you use the 'preview' of the OLE DB source?

Did you check twice the mapping tab in your OLE DB destination to make sure nothing is missing?

Have you used a data view right before the OLE DB Destination to check the values of column_b are shown correctly?

If the answer to those 3 questions is yes, I am affraid I could not help you.

Rafael Salas

|||Could there be an issue in executing the newid() function?|||

Argh, the problem was due to operator error: somehow the source component SQL statement had gotten out of sync with the corresponding variable. How embarrassing!

But many thanks to Rafael and Phil, who got me to examine the data flow task closely enough to discover my error.

case expression in where clause and null's

Using SQL Server 2005
I have a simple table example with two columns: FirstName varchar(20) and
LastName varchar(20)
I am doing something like this in a stored procedure where @.firstname and
@.lastname are passed in and @.lastname could be null
select * from table where FirstName = @.firstname and LastName =
COALESCE(@.LastName, LastName)
I am also using "set ansi_nulls off".
The query should give names where LastName is null if @.Lastname = null but
that's not happening. Why?
John DalbergBecause COALESCE returns the first non-NULL value. If @.LastName is null,
then it won't return @.LastName, it will Return LastName (the column, not the
variable).
Essentially making your stmt:
select * from table where FirstName = @.firstname and LastName = LastName
or rather
select * from table where FirstName = @.firstname
"John Dalberg" <nospam@.nospam.sss> wrote in message
news:20060405191639.387$oV@.newsreader.com...
> Using SQL Server 2005
> I have a simple table example with two columns: FirstName varchar(20) and
> LastName varchar(20)
> I am doing something like this in a stored procedure where @.firstname and
> @.lastname are passed in and @.lastname could be null
> select * from table where FirstName = @.firstname and LastName =
> COALESCE(@.LastName, LastName)
> I am also using "set ansi_nulls off".
> The query should give names where LastName is null if @.Lastname = null but
> that's not happening. Why?
> John Dalberg|||>The query should give names where LastName is null if @.Lastname = null but
>that's not happening. Why?
It sounds like this might be confusion over how NULL works.
If table.LastName IS NULL, and @.LastName IS NULL, then
COALESCE(@.LastName, LastName) will resolve to NULL. In that situation
the test:
LastName = COALESCE(@.LastName, LastName)
resolves to:
NULL = NULL
Which comparison will never resolve to TRUE. NULL is never equal to
anything, including another NULL. Consider these comparisons:
NULL = 'banana'
NULL <> 'banana'
NULL = NULL
NULL <> NULL
None of those can ever be resolved as TRUE, because equality (or
inequality) can only result from comparing something to something.
NULL is nothing, and can not be compared at all.
Roy Harvey
Beacon Falls, CT
On 05 Apr 2006 23:06:02 GMT, nospam@.nospam.sss (John Dalberg) wrote:

>Using SQL Server 2005
>I have a simple table example with two columns: FirstName varchar(20) and
>LastName varchar(20)
>I am doing something like this in a stored procedure where @.firstname and
>@.lastname are passed in and @.lastname could be null
>select * from table where FirstName = @.firstname and LastName =
>COALESCE(@.LastName, LastName)
>I am also using "set ansi_nulls off".
>The query should give names where LastName is null if @.Lastname = null but
>that's not happening. Why?
>John Dalberg|||Roy Harvey <roy_harvey@.snet.net> wrote:
> It sounds like this might be confusion over how NULL works.
> If table.LastName IS NULL, and @.LastName IS NULL, then
> COALESCE(@.LastName, LastName) will resolve to NULL. In that situation
> the test:
> LastName = COALESCE(@.LastName, LastName)
> resolves to:
> NULL = NULL
> Which comparison will never resolve to TRUE. NULL is never equal to
> anything, including another NULL. Consider these comparisons:
> NULL = 'banana'
> NULL <> 'banana'
> NULL = NULL
> NULL <> NULL
> None of those can ever be resolved as TRUE, because equality (or
> inequality) can only result from comparing something to something.
> NULL is nothing, and can not be compared at all.
But when you have set ansi_nulls off and run:
select * from table where lastname = null, it returns rows where lastname=
null
Doesn't that statement translate to:
select * from table where null = null ?
and when you set ansi_nulls on
one needs to write it as: select * from table where lastname is null ?
John Dalberg|||take a look at this
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 =@.v2
print 'equal'
else
print 'not equal'
go
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 is null and @.v2 is null
print 'Both null'
else
print 'both not null'
go
set ansi_nulls off
go
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 =@.v2
print 'equal'
else
print 'not equal'
go
set ansi_nulls on
go
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||"Paul Wehland" <PaulWe@.REMOVE-ME.Avanade.com> wrote:
> Because COALESCE returns the first non-NULL value. If @.LastName is null,
> then it won't return @.LastName, it will Return LastName (the column, not
> the variable).
> Essentially making your stmt:
> select * from table where FirstName = @.firstname and LastName =
> LastName or rather
> select * from table where FirstName = @.firstname
What does COALESCE return in this case when there's no none null values?
(not that it makes sense)
select * from table where FirstName = @.firstname and LastName =
COALESCE(@.LastName, @.LastName)
Would that translate to:
select * from table where FirstName = @.firstname and LastName = null ?
Doesn't 'set ansi_null off' make 'null =null' evaluate to true?
Anyways, I need the where clause to include the lastname if @.lastname has a
value and return null lastnames rows if @.lastname is null. I couldn't find
a way to do it in a CASE expression. I can do it in a dynamic sql.
John Dalberg
> "John Dalberg" <nospam@.nospam.sss> wrote in message
> news:20060405191639.387$oV@.newsreader.com...|||>>What does COALESCE return in this case when there's no none null values?
(not that it makes sense)
COALESCE will return the first non NULL value
Here is an example
declare @.v1 int,@.v2 int,@.v3 int,@.v4 int
select @.v1 = null,@.v2 = null,@.v3 =4,@.v4 =8
select coalesce(@.v1,@.v2,@.v3,@.v4)
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||"SQL" <denis.gobo@.gmail.com> wrote:
> take a look at this
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 =@.v2
> print 'equal'
> else
> print 'not equal'
> go
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 is null and @.v2 is null
> print 'Both null'
> else
> print 'both not null'
> go
> set ansi_nulls off
> go
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 =@.v2
> print 'equal'
> else
> print 'not equal'
> go
> set ansi_nulls on
> go
I understand the principles. That's why I included set ansi_nulls off in my
clarification.|||It is easier to communicate using DDL. I've added DDL at the end of this tex
t so we can use that
from here on.
Let me see if I can re-phrase your question:
You have some rows which has NULL on the lastname column. You want to find t
hem using ANSI_NULLS OFF
and by passing in NULL in the @.lastname parameter of your stored procedure.
So, in the query, you
have the following condition:
AND LastName = COALESCE(@.LastName, LastName)
So, if if you pass NULL for the @.lastname parameter, the condition will tran
slate to:
AND LastName = LastName
And you wonder why that will not return the rows where you have NULL in the
lastname column. Is that
correct?
If so, read in Books Online about SET ANSI_NULLS OFF. It only comments about
comparsions between a
column and NULL, not between two columns where each has NULL. I guess that t
his is how Sybase
defined it some 20 years ago, and MS has kapt this behavior. You could do a
BOL feedback and ask
them to clarify this in the 2005 BOL.
DDL:
USE tempdb
CREATE TABLE t(firstname varchar(30) not null, lastname varchar(30) null)
insert into t (firstname, lastname)
VALUES('John', 'Dalberg')
insert into t (firstname, lastname)
VALUES('Franz', NULL)
SET ANSI_NULLS OFF
GO
CREATE PROC p
@.firstname varchar(30), @.lastname varchar(30)
AS
SELECT firstname, lastname
from t
where FirstName = @.firstname
AND LastName = COALESCE(@.LastName, LastName)
GO
EXEC p 'John', 'Dalberg'
EXEC p 'John', NULL
EXEC p 'Franz', NULL
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"John Dalberg" <nospam@.nospam.sss> wrote in message news:20060406121819.765$iB@.newsreader.c
om...
> Roy Harvey <roy_harvey@.snet.net> wrote:
> But when you have set ansi_nulls off and run:
> select * from table where lastname = null, it returns rows where lastname=
> null
> Doesn't that statement translate to:
> select * from table where null = null ?
> and when you set ansi_nulls on
> one needs to write it as: select * from table where lastname is null ?
> John Dalberg|||"Paul Wehland" <PaulWe@.REMOVE-ME.Avanade.com> wrote:
> Because COALESCE returns the first non-NULL value. If @.LastName is null,
> then it won't return @.LastName, it will Return LastName (the column, not
> the variable).
> Essentially making your stmt:
> select * from table where FirstName = ffirstname and LastName =
> LastName or rather
Right and that's the way it should work so when you have ansi_nulls off,
lastname = lastname will return rows where lastname is null and it will not
return these rows if set ansi_nulls on. I am missing what was wrong in my
statement.
so:
set ansi_nulls off;select * from table where FirstName = firstname and
LastName =lastname
&
select * from table
both return the same # of rows regardless whether lastname is null or not.
John Dalbergsql

Monday, March 19, 2012

CASE / NULL Problem

Hello!
I want to set a value depending on a condition but I can't seem to get it
right when the original value is NULL.
Select bla, bla... FROM bla...
*****************************
DellyDate=CASE DelivDate
WHEN NULL THEN
'1999-12-31'
ELSE
LEFT(DelivDate,4) + '-' + Substring(DelivDate,5,2) + '-' +
RIGHT(DelivDate,2)
END
***********************************'
This code parses successfully, but even when DelivDate actually is NULL,
DellyDate never has the value '1999-12-31'. What am I doing wrong here?You'll need to use IS NULL.
DellyDate=CASE WHEN DelivDate IS NULL
THEN
'1999-12-31'
ELSE
LEFT(DelivDate,4) + '-' + Substring(DelivDate,5,2) + '-' +
RIGHT(DelivDate,2)
END
or alternatively
DellyDate=COALESCE(LEFT(DelivDate,4) + '-' + Substring(DelivDate,5,2) +
'-' +
RIGHT(DelivDate,2) ,'1999-12-31' )|||DellyDate = CASE WHEN DelivDate IS NULL THEN '1999-12-13' ELSE .... END
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Clarkie" <clarkbones@.rock.sendmenot.etmail.com> wrote in message
news:eKVi$lQJGHA.1728@.TK2MSFTNGP09.phx.gbl...
> Hello!
> I want to set a value depending on a condition but I can't seem to get it
> right when the original value is NULL.
> Select bla, bla... FROM bla...
> *****************************
> DellyDate=CASE DelivDate
> WHEN NULL THEN
> '1999-12-31'
> ELSE
> LEFT(DelivDate,4) + '-' + Substring(DelivDate,5,2) + '-' +
> RIGHT(DelivDate,2)
> END
> ***********************************'
> This code parses successfully, but even when DelivDate actually is NULL,
> DellyDate never has the value '1999-12-31'. What am I doing wrong here?
>|||you could also
coalesce(convert(varchar(10), convert(datetme, DelivDate), 120),
'1999-12-31')
"Clarkie" wrote:

> Hello!
> I want to set a value depending on a condition but I can't seem to get it
> right when the original value is NULL.
> Select bla, bla... FROM bla...
> *****************************
> DellyDate=CASE DelivDate
> WHEN NULL THEN
> '1999-12-31'
> ELSE
> LEFT(DelivDate,4) + '-' + Substring(DelivDate,5,2) + '-' +
> RIGHT(DelivDate,2)
> END
> ***********************************'
> This code parses successfully, but even when DelivDate actually is NULL,
> DellyDate never has the value '1999-12-31'. What am I doing wrong here?
>
>|||Read the definition of the CASE expression. You are using a shorthand
for
SELECT ..
FROM ..
WHERE delly_date
=CASE WHEN delly_date = NULL -- always UNKNOWN !!!!
THEN '1999-12-31'
ELSE .. END ;|||Thanks for all the answers!
Problem solved!
//Clarkie
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1138581718.965490.84740@.g14g2000cwa.googlegroups.com...
> Read the definition of the CASE expression. You are using a shorthand
> for
> SELECT ..
> FROM ..
> WHERE delly_date
> =CASE WHEN delly_date = NULL -- always UNKNOWN !!!!
> THEN '1999-12-31'
> ELSE .. END ;
>

Cascading Referential Integrity Constraints

In a master-detail one-to-many relationship, I have the foreign key set to '
allow null'. I would like, in this particular case, to automatically have th
e foreign key set to null when the master/one record is deleted.
My understanding from the 'books on line' is that cascading a delete will al
ways delete the detail/many records when the master/one record is deleted. I
f the foreign key is nullable, would it not make sense to null it, and if it
is not nullable to delete
the detail/many records?
Is there any efficient way to set a table up so that foreign keys are automa
tically nulled when the primary key record is deleted?That functionality won't be available until the next release of SQL Server
(Yukon). Meanwhile, you will have to handle RI through triggers in that
case. This link may be useful:
http://msdn.microsoft.com/library/d...efintegrity.asp
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"John Austin" <John.Austin@.ManagedNewsgroups.com> wrote in message
news:025F9D33-F01D-43AA-BF12-09C50AAD4670@.microsoft.com...
In a master-detail one-to-many relationship, I have the foreign key set to
'allow null'. I would like, in this particular case, to automatically have
the foreign key set to null when the master/one record is deleted.
My understanding from the 'books on line' is that cascading a delete will
always delete the detail/many records when the master/one record is deleted.
If the foreign key is nullable, would it not make sense to null it, and if
it is not nullable to delete the detail/many records?
Is there any efficient way to set a table up so that foreign keys are
automatically nulled when the primary key record is deleted?

Thursday, March 8, 2012

Cascade set to null on delete.

Hi all,

I am using SQL Server 2000 and am trying to perform a basic delete query on a table called ClientType. The only child table of this is called Client. The relationship between the tables has a cascade action of cascade update and when I try to perform the delete operation, I get the error "DELETE statement conflicted with COLUMN REFERENCE constraint". The foreign key field accepts nulls and has a defauilt value of null. Now, am I being completely dense or shouldn't the cascade update set the foreign key values to null?

Regards,

Stephen.

Could you please send over the DDL for the table and the constraints, thanks.

HTH, Jens SUessmeyer.

http://www.sqlserver2005.de|||

Here you go:
...

CREATE TABLE [dbo].[ClientType] (
[ClientTypeId] [int] IDENTITY (1, 1) NOT NULL ,
[ObjectVersion] [int] NULL ,
[Type] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Client] (
[ClientId] [int] IDENTITY (1, 1) NOT NULL ,
[ObjectVersion] [int] NULL ,
[ClientTypeId] [int] NULL ,
[ReferenceNumber] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Password] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Title] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Forename] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Initial] [varchar] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Surname] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[DateOfBirth] [datetime] NULL ,
[DateRegistered] [datetime] NULL ,
[Address1] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Address2] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Address3] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[City] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[County] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Postcode] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Country] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Telephone1] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Telephone2] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Telephone3] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Fax] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[EMail] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[URL] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Position] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Overview] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[InternalOverview] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Comments] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[CV] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[HoldingCompanyName] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[ClientType] WITH NOCHECK ADD
CONSTRAINT [PK_ClientType] PRIMARY KEY CLUSTERED
(
[ClientTypeId]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Client] WITH NOCHECK ADD
CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED
(
[ClientId]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ClientType] ADD
CONSTRAINT [DF_ClientType_ObjectVersion] DEFAULT (0) FOR [ObjectVersion]
GO

ALTER TABLE [dbo].[Client] ADD
CONSTRAINT [DF_Client_ObjectVersion] DEFAULT (0) FOR [ObjectVersion],
CONSTRAINT [DF_Client_ClientTypeId] DEFAULT (null) FOR [ClientTypeId]
GO

ALTER TABLE [dbo].[Client] ADD
CONSTRAINT [FK_Client_ClientType] FOREIGN KEY
(
[ClientTypeId]
) REFERENCES [dbo].[ClientType] (
[ClientTypeId]
) ON UPDATE CASCADE
GO

...

Regards,

Stephen.

|||OK, you just defined the Cascade on the update, if you delete a row and the child table contains rows for that parent row and you did not define a cascade delete on the parent table, this error message will come up.

You wil have to add: ON DELETE CASCADE

HTH; Jens Suessmeyer.

http://www.sqlserver2005.de|||

Thanks for the response. I do understand that adding cascade delete would get rid of the error but will that not result in the child rows being deleted? I only want the foreign keys to be set to null, not have the entire related record dropped from the table.

Regards,

Stephen.

|||OK, then you will have to use the ON DELETE SET NULL.

HTH; Jens Suessmeyer.

http://www.sqlserver2005.de|||OK. I gave that a go, but I just get an error "incorrect syntax near the keyword 'SET'".|||

Sorry, I re-read your first post and saw that you are using SQL Server 2k. SET NULL is a new feature for SQL 2k5. In SQL Server 2000 you probably would use no constraint in that case and do the work with triggers, in that case an update trigger.

Sorry for confusing you :-)


HTH, Jens SUessmeyer.

http://www.sqlserver2005.de

|||

OK. I'll look into that.

Thanks for your help. Its much appreciated.

Regards,

Stephen.

CASCADE DELETE (No Action)

Hi,
I have a table that I want to create a Foreign Key constraint on.
This column has NULL values.
I want to create the Foreign Key with a CASCADE DELETE NO ACTION.
I have done this through the script below as I am not sure if this can be do
ne through the GUI in Enterprise Manager. I CAN create a FK through the Ente
rprise Manager GUI for a CASCADE ON DELETE UPDATE and uncheck the check box
"check existing data on cre
ation" and it works fine. Can I do a "ON DELETE NO ACTION" through the GUI a
nd not check existing data on creation?
If not how can I modify my script below to not check the data on creating th
e Foreign Key as this is why I think my Script is not working.
Maybe I should have a Trigger instead?
Any advice/info is much appreciated.
Here is my script I wrote...
ALTER TABLE [dbo].[T_CMT_CONTENT] ADD
CONSTRAINT [FK_T_CMT_CONTENT_T_NWKF_WORKFLOW] FOREIGN KEY
(
[WKF_WORKFLOW_ID]
) REFERENCES [dbo].[T_NWKF_WORKFLOW] (
[WKF_WORKFLOW_ID]
)
ON DELETE NO ACTION
GO
Thanks,
C.On Thu, 27 May 2004 09:21:06 -0700, C wrote:
(snip)
Hi C,
Answered in microsoft.public.sqlserver.programming.
Please don't crosspost!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

CASCADE DELETE (No Action)

Hi,
I have a table that I want to create a Foreign Key constraint on.
This column has NULL values.
I want to create the Foreign Key with a CASCADE DELETE NO ACTION.
I have done this through the script below as I am not sure if this can be done through the GUI in Enterprise Manager. I CAN create a FK through the Enterprise Manager GUI for a CASCADE ON DELETE UPDATE and uncheck the check box "check existing data on cre
ation" and it works fine. Can I do a "ON DELETE NO ACTION" through the GUI and not check existing data on creation?
If not how can I modify my script below to not check the data on creating the Foreign Key as this is why I think my Script is not working.
Maybe I should have a Trigger instead?
Any advice/info is much appreciated.
Here is my script I wrote...
ALTER TABLE [dbo].[T_CMT_CONTENT] ADD
CONSTRAINT [FK_T_CMT_CONTENT_T_NWKF_WORKFLOW] FOREIGN KEY
(
[WKF_WORKFLOW_ID]
) REFERENCES [dbo].[T_NWKF_WORKFLOW] (
[WKF_WORKFLOW_ID]
)
ON DELETE NO ACTION
GO
Thanks,
C.
On Thu, 27 May 2004 09:21:06 -0700, C wrote:
(snip)
Hi C,
Answered in microsoft.public.sqlserver.programming.
Please don't crosspost!
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)