How to use if else in SQL Server stored procedure - sql-server

Stored procedure:
CREATE PROCEDURE validate
#blockID VARCHAR(255)
AS
BEGIN
IF #blockID = (SELECT blockID FROM block WHERE blockID = #blockID)
PRINT 'exists'
IF #blockID != (SELECT blockID FROM block WHERE blockID = #blockID)
PRINT 'does not exist'
END
When input the wrong one blockID, the 2nd if conditions does not work.

You probably want to use EXISTS.
CREATE PROCEDURE validate
#blockID VARCHAR(255)
AS
BEGIN
IF EXISTS (SELECT blockID FROM block WHERE blockID = #blockID)
PRINT'exists'
ELSE
PRINT'not exists'
END

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;'
...
...

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

add custom messages in a stored procedure

i want to add some messages in my stored procedure according to if else condition how can i do that. the issue is i have three tables team , account and user. i want to delete the teamA in team table only on the condition if there is not any account and user is related to that team. i have the stored procedure which is working fine but i want to check the condition and want to add some custom messages using if else . please help here is my code.
Create PROCEDURE sp_DeleteTeam
#pTeamId int
AS
BEGIN
SET NOCOUNT ON;
update t
set t.Deleted =1
from Team t
where t.TeamId = #pTeamId
And Not Exists (Select 1 from [User] where TeamId = #pTeamId)
And Not Exists (Select 1 from Account where TeamId = #pTeamId)
END
Don't use the prefix sp_ for user stored procedures as that is reserved for system procs.
Below is an example that returns the message using RAISERROR. A severity of 11 or higher as in this example will raise an exception in the application. Severity of 10 or lower will generate an informational message.
CREATE PROCEDURE usp_DeleteTeam #pTeamId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Message varchar(2047);
UPDATE t
SET t.Deleted = 1
FROM Team t
WHERE t.TeamId = #pTeamId
AND NOT EXISTS ( SELECT 1
FROM [User]
WHERE TeamId = #pTeamId )
AND NOT EXISTS ( SELECT 1
FROM Account
WHERE TeamId = #pTeamId );
IF ##ROWCOUNT = 0
BEGIN
IF NOT EXISTS ( SELECT *
FROM Team
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = 'does not exist in Team table';
END;
IF EXISTS ( SELECT *
FROM [User]
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = COALESCE(#Message + ', ', '')
+ 'already exists in User table';
END;
IF EXISTS ( SELECT *
FROM Account
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = COALESCE(#Message + ', ', '')
+ 'already exists in Account table';
END;
SET #Message = 'Team %d: ' + #Message
RAISERROR(#Message, 11, 0, #pTeamId);
END;
END;
Use the below SP to use print or select message.
Create PROCEDURE sp_DeleteTeam
#pTeamId int
AS
BEGIN
SET NOCOUNT ON;
IF ((NOT EXISTS (SELECT TOP 1 FROM [User] WHERE TeamId = #pTeamId)) AND (Not EXISTS (SELECT TOP 1 FROM Account WHERE TeamId = #pTeamId)))
BEGIN
UPDATE T
SET T.Deleted = 1
FROM Team t
WHERE T.TeamId = #pTeamId
SELECT 'Not exist - Table updated' AS Message
--PRINT 'Not exist - Table updated'
END
ELSE
BEGIN
SELECT 'Already exist - Table not updated.' AS Message
--PRINT 'Already exist - Table not updated.'
END
END
As far as I understood you just want to see if it executed sucessfully. If the stored Procedure is being called In some Applciation, At the end, Give a select statement as
SELECT 'Your message' AS Message
Then in application store the result in Dataset and retrieve your message,
If you are not using it in any application, then simply use
print 'your message'
OR may be try to be more specific and elaborate you problem a bit clearly.

Sql Server Stored procedure returns -1

I am writing code on entity framework 6.0, linq on asp.net, sql server platform.
I've written a stored procedure which supposed to return an output value (0 or 1)
Firstly I wrote SP by using output parameter as follows:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50),
#val int output
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
set #val=1
end
if not exists(select * from Users where #oNo=sNo and #pw=password)
begin
set #val=0
end
end
Didnt work. It returned -1. Then I changed SP like this:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50)
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
return 1
end
else
begin
return 0
end
end
Each ways stored procedure returns only -1
Can you help me please, where am i doing wrong?
Try to replace "return" by "select".
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
select 1
end
else
begin
select 0
end

T - SQL statement IF EXIST SELECT and INSERT

How can I make this possible..really need advice? I want to get the id where my condition is met, then used it in my queries.
IF EXISTS (Select sn_id as snid FROM device.sn WHERE dname_id = 62 and sn_value = '123415')
BEGIN
SELECT MAX(id) AS maxid FROM device.list
INSERT INTO parts (sn_id,device_id) VALUES (snid, maxid)
END
ELSE
BEGIN
PRINT 'id does not exist'
return
END
You can use variables to store the results from the two queries and then use those values in your INSERT statement.
If you're using Microsoft SQL Server then the following may work (but there may be superficial syntax errors as it hasn't been tested). Note that I've assumed the type of your columns is int.
DECLARE #snid int
SET #snid = NULL
Select #snid = sn_id FROM device.sn WHERE dname_id = 62 and sn_value = '123415'
IF #snid IS NULL
BEGIN
PRINT 'id does not exist'
END
ELSE
BEGIN
DECLARE #maxid int
SELECT #maxid = MAX(id) AS maxid FROM device.list
INSERT INTO parts (sn_id,device_id) VALUES (#snid, #maxid)
END
In SQLServer. This script at first insert records and after checks count of the inserted rows
INSERT INTO parts (sn_id, device_id)
SELECT sn_id, (SELECT MAX(id) FROM device.list)
FROM device.sn
WHERE dname_id = 62 and sn_value = '123415'
IF ##ROWCOUNT = 0 PRINT 'id does not exist'
Declare #snid int=null
Declare #maxid int=1 -- if no value exists in device.list table
set #snid = (select sn_id from device.sn WHERE dname_id = 62 and sn_value = '123415')
set #maxid = (select MAX(id) AS maxid FROM device.list)
if #snid is not null
Begin
insert into parts(sn_id,device_id)
values(#snid,#maxid)
End
else
Begin
print 'ID does not exist'
End

Resources