Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick SQL Syntax Question

I have a standard insert into / select statement that is formatted similar to this:

insert into Table
( ...,
 ...)

select
field1,
field2,
field3,
field4,
fieldetc
from .... etc 

There are three specific fields in the select statement that will need different values selected depending on another field, let's call it checker and the three fields are field2, field3, and field 4. The values will either be a 0 or in the other situation will need a case when. My question is, how do I format an if/else statement so it will work within the select statement? How I have it now is like this:

select
field1data,
if checker = 'A' or checker is null
begin
  0,
  0,
  0,
end
else 
begin
case when ... then ... else ... end,
case when ... then ... else ... end,
case when ... then ... else ... end,
end
fieldetcdata
from... etc

This is returning errors. How can I format this so it will work correctly, either selecting zeroes for these three fields or running through my case when statements in the other situation. Thanks!

like image 235
Nard Dog Avatar asked Jan 31 '26 11:01

Nard Dog


1 Answers

You'll need to specify case statement for each field separately.

Select  field1data,

        Case When IsNull(Checker,'A') = 'A' Then 0
             When Cond1 Then Whatever1
             ...
             Else ...
        End,

        Case When IsNull(Checker,'A') = 'A' Then 0
             When Cond2 Then Whatever1
             ...
             Else ...
        End,

        Case When IsNull(Checker,'A') = 'A' Then 0
             When Cond2 Then Whatever1
             ...
             ELSE ...
        End,

        fieldetcdata
From    ETC
like image 131
YetAnotherUser Avatar answered Feb 03 '26 05:02

YetAnotherUser