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
Related
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;'
...
...
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...
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
Are there any rules defined for grouping the T-SQL statements under the BEGIN...END block ?
Because when I try the BEGIN...END block inside the CASE statement OR IIF statement, it fails.
I need BEGIN...END block because there are multiple operations that I want to perform under the CASE result.
SELECT
CASE #ChargePaid
WHEN 1 THEN
BEGIN
SELECT 'Paid'
END
WHEN 0 THEN
BEGIN
SELECT 'Not Paid'
END
END
OR
SELECT IIF( #ChargePaid > 0, BEGIN SELECT 'Paid' END , BEGIN SELECT 'Not Paid' END )
EDIT:
IF #cond = 'First'
WITH CTE AS (
SELECT 'A missing' Result
UNION
SELECT 'B missing' Result
UNION
SELECT 'C missing' Result
)
SET #msg = SELECT Result from CTE
IF #cond = 'Second'
WITH CTE AS (
SELECT 'A missing' Result
UNION
SELECT 'B missing' Result
UNION
SELECT 'C missing' Result
)
SET #msg = SELECT Result from CTE
IF #ChargePaid = 0
...
Some code goes here to generate the message.
Then I store the actual message into #msg variable.
...
In the end I store the #msg values (I trim the #msg if it requires) to the table.
What I want is:
I want to validate the #ChargePaid condition.
If it comes false, I want to avoid further processing for optimization of code & store charge missing info to #msg variable\table.
BEGIN / END delimit program statements.
Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed.
CASE blocks accept expressions.
Evaluates a list of conditions and returns one of multiple possible result expressions.
So you are trying to fit a square peg in a round hole.
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