Case statement in SQL Server 2005 - sql-server

I am not sure what to use in this scenario, but I think a Case statement is apt.
I do not know the syntax however. Can someone please guide me?
I have a variable called #Action which can have about 30 different values.
I want to do something like this
CASE
WHEN #Action = 'InsertTbl1' THEN
BEGIN
-- Some Insert statements and one update statements
END
WHEN #Action = 'RecalculateCol3' THEN
BEGIN
-- Some update statements
END
WHEN #Action = 'Closed' THEN
BEGIN
-- Some delete statements and some update statements
END
--- and so on.....
ELSE
BEGIN
END
END

Suggest a structure of IF and ELSE IF to mimic a switch.
IF #MyVar = 'Foo'
BEGIN
--react to Foo
END
ELSE IF #MyVar = 'Bar'
BEGIN
--react to Bar
END
ELSE
BEGIN
--default case.
END

Yes, you can use Else If. For example:
declare #temp int
set #temp = 3
if #temp = 1
print '1'
else if #temp > 1 and #temp < 3
print '2'
else if #temp >= 3
print '3'
I would still think about breaking it up into separate procedures as suggested by others

Related

SQL ELSE block still throws error when IF condition is true

I have the following T-SQL script that copies the value of an old column into a new one, then drops the old column. See here:
--step 1: create new column
IF NOT EXISTS(SELECT 1 from sys.columns
WHERE Name = N'UserColumn2'
AND Object_ID = Object_ID(N'Account'))
BEGIN
ALTER TABLE Account
ADD UserColumn2 int null
;
END
GO
;
--step 2: copy and drop
IF NOT EXISTS(SELECT 1 from sys.columns
WHERE Name = N'UserColumn1'
AND Object_ID = Object_ID(N'Account'))
BEGIN
PRINT 'Column ''UserColumn1'' does not exist.';
END
ELSE
BEGIN
UPDATE Account
SET UserColumn2 = UserColumn1
WHERE UserColumn1 is not null
;
BEGIN TRY
Declare #count int;
SELECT #count = Count(AccountID)
FROM Account
WHERE UserColumn2 <> UserColumn1
;
IF #count > 0
BEGIN
--PRINT 'Not all records were properly updated. UserColumn1 has not been dropped.';
THROW 50000,'Not all records were properly updated. UserColumn1 has not been dropped.',1
;
END
ELSE
BEGIN
ALTER TABLE Account
DROP Column UserColumn1
;
END
END TRY
BEGIN CATCH THROW; END CATCH
END
GO
;
The first step runs correctly but the second step still throws an error in the ELSE block even if the UserColumn1 column doesn't exist:
(note: this actually throws on line 24 for the code here. The code in my SSMS doesn't have the comments for 'step 1', etc.)
Why is this happening and how can I prevent it?
I've tried removing the NOT and moving the instructions out of the ELSE block but the behavior did not change. I've also tried writing the beginning of the second step like this:
IF (SELECT 1 from sys.columns
WHERE Name = N'UserColumn1'
AND Object_ID = Object_ID(N'Account')) <> null
and I get the same result.
The issue is that the entire sql text is parsed and compiled before it's executed, the error is being thrown at compile time.
You could workaround it by executing the update statement in its own process using dynamic sql - although there is nothing dynamic in this usage, it simply defers the compilation and execution of the update statement where it only happens in your else condition:
IF NOT EXISTS(SELECT 1 from sys.columns
WHERE Name = N'UserColumn1'
AND Object_ID = Object_ID(N'Account'))
BEGIN
PRINT 'Column ''UserColumn1'' does not exist.';
END
ELSE
BEGIN
EXEC sp_executesql N'
UPDATE Account
SET UserColumn2 = UserColumn1
WHERE UserColumn1 is not null;'
...
...

How can I increase stored procedure performance with multiple if else statement?

I have a stored procedure with multiple if-elseif- else statements. When I try to remove this if elseif statement and execute only single portion of that query, it returns results very fast, but when use this query with multiple another queries using if-elseif case statement, then it takes too much time...
For example:
if #Status = 1
begin
select .....
end
else if #Status = 2
begin
select .....
end
else if #Status = 3
begin
select .....
end
else if....
There are many more else if statements in this stored procedure..
Although it may be in some "don't do this" books, you can try to create a stored procedure for each status value and call it directly by building a dynamic TSQL statement ("exec yourproc_" + statusValue).
create proc youproc_1 as
begin
select your_data_for_status1;
end;
create proc youproc_2 as
begin
select your_data_for_status2;
end;
etc...

Stored Proc that picks from 2 different Select Statements

I have the following Select statements, I need to create a stored proc that will choose which statement to run, guessing this would have to be based on variables (newb here). I've read about Passed Parameters but have not seen an example that applies to this situation in my searches, please help me out.
I am in SQL Server 2014.
First statement
select
cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
case
when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
else 'no alert'
end as alert_status
from activity_table
Second Statement
select
cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
case
when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
else 'no alert'
end as alert_status
from activity_table
Will something like this work
CREATE PROCEDURE ChooseWhichOne
#Selection BIT
AS
BEGIN
IF #Selection = 0
BEGIN
select
cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
case
when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
else 'no alert'
end as alert_status
from activity_table
END
ELSE
BEGIN
select
cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
case
when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
else 'no alert'
end as alert_status
from activity_table
END
RETURN 0
END
AND to execute the stored PROCEDURE
EXEC dbo.ChooseWhichOne #Selection = 0 -- bit
EXEC dbo.ChooseWhichOne #Selection = 1 -- bit

T SQL if column exists then (if it has value X then (

I need to perform the following logical clause:
If column is present and it has certain value then do something.
If not, then do something else.
IF EXISTS(
SELECT *
FROM sys.columns
WHERE Name = N'legacyoptions'
AND Object_ID = Object_ID(N'config '))
BEGIN
if ( select legacyoptions from config)=1
begin
Do stuff when legacy=1
end
else begin
Do stuff when legacy !=1
END
else
begin
do stuff when legacy is not present
end
However, this does not work in case legacyoptions is not present
Here is the way using TRY CATCH block and a dynamic SQL so this block of code will be compiled without table config and/or legacyoptionsfield in the database.
BEGIN TRY
DECLARE #legacyoptions int;
EXECUTE sp_executesql N'select TOP 1 #legacyoptions=legacyoptions from config',
N'#legacyoptions int OUTPUT',
#legacyoptions OUTPUT;
if #legacyoptions=1
begin
-- Do stuff when legacy=1
end
ELSE
BEGIN
-- Do stuff when legacy !=1
END
END TRY
BEGIN CATCH
-- do stuff when legacy is not present
END CATCH
try this :(i guess you are leaving an end of if)
IF EXISTS(
SELECT *
FROM sys.columns
WHERE Name = N'legacyoptions'
AND Object_ID = Object_ID(N'config '))
BEGIN
if ( select legacyoptions from config)=1
begin
Do stuff when legacy=1
end
else begin
Do stuff when legacy !=1
END
end
else
begin
do stuff when legacy is not present
end
This works, but seems stupid to me.
IF EXISTS( SELECT * FROM sys.columns WHERE Name = N'legacyoptions' AND Object_ID = Object_ID(N'config '))
BEGIN
exec('
if (select legacyoptions from config)=1
begin
print ''Config==1''
end
else
begin
print ''Config!=1''
end
')
end
else
begin
print 'no legacy'
end

Help with an IF in SQL SERVER Stored procedure

can anyone help me with construction of an IF in a stored procedure in sql server.
Basically I have a simple stored procedure but I now need to pass in a new input parameter which depending if it is true I pass the value D and if its false I pass the value A. But the change is in the middle of a subquery.. let me explain... here is the stored procedure. basically if I send in True for ReturnOldStatus I execute the subquery ItemStatus='D' and if it is false then i pass in ItemStatus='A'
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(
#IdOffice Int,
#ReturnOldStatus bit
)
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE
ItemStatus= 'D') // This needs to be ItemStatus ='A' if FALSE is passed in on the input param
Any ideas??
Thanks
I would solve it like this:
declare #itemStatus varchar(1);
if (#inputParam = 'FALSE')
begin
set #itemStatus = 'A'
end
else
set #itemStatus = 'D'
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE ItemStatus= #itemStatus)
)
T-Sql is not my native language, so there may be errors in there...
Just use the T-SQL if statement:
IF #ReturnOldStatus = 0
BEGIN
--Some statements
END
ELSE
BEGIN
--Some other statements
END
I think this will suffice for your problem. If not, look into the DECLARE/SET statements in TSQL.
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(#IdOffice Int,
#ReturnOldStatus bit )
AS BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE IdOffice = #IdOffice
AND (V.OffType NOT IN (SELECT * FROM MiscOff
WHERE (ItemStatus= 'D' AND #ReturnOldStatus = 1)
OR
(ItemStatus= 'A' AND #ReturnOldStatus = 0)
)

Resources