If else doesn't work in stored procedures - sql-server

I have two stored procedures to select and insert values.When I choose an item from Listbox and click the add button, the code calls SP$select. Then a new Form appears and I give the data into the textbox. When I click save button, SP$insert works. But all the data can be only inserted into the first(Base) column. When I do all actions in SP$insert (select and insert) then it doesn't work. What's wrong with it?
Procedure 1 [SP$select]
use env
go
create proc [SP$select](
#p2 nvarchar(20),
#debug bit = 0)
as
begin
set nocount on
begin try
if #p2='User Name'
begin
SELECT user_name FROM env.dbo.Base
end
else if #p2='Serial Number'
begin
SELECT ser_num FROM env.dbo.Base
end
end try
begin catch
IF #debug = 1
throw;
end catch
end
set nocount off
go
Procedure 2 [SP$insert]
use env
go
create proc [SP$insert](
#p1 nvarchar(100),
#id int output,
#debug bit = 0)
as
begin
set nocount on
begin try
if exists(select user_name from env.dbo.Base)
begin
INSERT INTO envanter.dbo.Base(user_name) VALUES (#p1)
SELECT #id = ##IDENTITY
end
else if exists(select ser_num from env.dbo.Base)
begin
INSERT INTO env.dbo.Base(ser_num) VALUES (#p1)
SELECT #id = ##IDENTITY
end
end try
begin catch
if #debug = 1
throw;
end catch
set nocount off
end
go

try this code
use env
go
create proc [SP$insert](
#p1 nvarchar(100),
#id int output,
#debug bit = 0)
as
begin
set nocount on
begin try
if exists(select user_name from env.dbo.Base)
begin
INSERT INTO envanter.dbo.Base(user_name) VALUES (#p1)
SELECT #id = ##IDENTITY
end
if exists(select ser_num from env.dbo.Base)
begin
INSERT INTO env.dbo.Base(ser_num) VALUES (#p1)
SELECT #id = ##IDENTITY
end
end try
begin catch
if #debug = 1
throw;
end catch
set nocount off
end
go

Not sure what you are trying to do here. If there is at least one row on table Base the statement "if exists(select user_name from env.dbo.Base)" whill always be TRUE regardless of whether the user_name value is null or not, therefore the "else if" part will never happen.

Related

sql query to delete and return message

I want to write some thing like that query:
BEGIN
DECLARE #Unaloacte varchar(200);
DECLARE #Total int;
DECLARE #Flag int;
SET #Unaloacte =( Select count(PD.PropertyDetailId) from PropertyDetail AS PD join
SiteDetail AS SD ON PD.SiteDetailId=SD.SiteDetailId Where PD.CustomerId<1 and PD.SiteDetailId=27);
SET #Total= (Select count(PropertyDetailId) as Total_Count from PropertyDetail where SiteDetailId=27) ;
if( #Unaloacte = #Total)
Delete something and display message
print"Delete";
else
print"Not able to delete"
END
I hope you understand my problem.
You can try like this:
DECLARE #Msg VARCHAR(200)
if( #Unaloacte = #Total)
BEGIN
BEGIN TRAN
DELETE something
SELECT #Msg = CAST(##ROWCOUNT AS VARCHAR(10)) + ' are deleted'
RAISERROR (#Msg, 0, 1) WITH NOWAIT
COMMIT
END
ELSE
BEGIN
SELECT 'Not able to delete'
END
Also I would recommend you to use BEGIN TRAN and COMMIT if you are going to use in Production.
You can check this by USING ##ROWCOUNT and SET NOCOUNT ON
SET NOCOUNT ON
DELETE FROM TableName
IF ##ROWCOUNT > 0
PRINT 'Record Deleted'
ELSE
PRINT 'Record Not Deleted'
Here SET NOCOUNT ON is used since we dont want to see number of rows affected message.

Retrieving a particular value in SQL Server

I have this stored procedure that has a value:
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
DECLARE #return_value int
DECLARE #media_id uniqueidentifier
'INSERT SQL STATEMENT HERE
SELECT [media_id] FROM [media] WHERE 1 = 1
-- One row affected
RETURN 1
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
-- Rollback, no row affected
RETURN 0
END CATCH;
I want to call the [media_id] value from another stored procedure. How do I get that value?
Table Definition
CREATE TABLE MY_EMPLOYEE
(EMPID INT, NAME VARCHAR(20),
LANGUAGEID INT , ID UNIQUEIDENTIFIER DEFAULT NEWID())
GO
Stored Procedure
ALTER PROCEDURE usp_ProcName
#Emp_ID INT = null,
#Name VARCHAR(20) = null,
#LanguageID int = null,
#NewID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
INSERT INTO [Practice_DB].[dbo].[MY_EMPLOYEE](EMPID, NAME, LANGUAGEID)
VALUES (#Emp_ID, #Name, #LanguageID);
-- Populating the OUTPUT variable using the other variables that were passed
-- for INSERT statement.
SELECT #NewID = ID
FROM [Practice_DB].[dbo].[MY_EMPLOYEE]
WHERE EMPID = #Emp_ID
-- One row affected
COMMIT TRANSACTION
RETURN 1
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
-- Rollback, no row affected
RETURN 0
END CATCH
END
GO
Calling Stored Procedure
DECLARE #value int, #ID VARCHAR(100)
EXECUTE #value = usp_ProcName
#Emp_ID = 50,
#Name = 'John',
#LanguageID = 50,
#NewID = #ID OUTPUT --<-- passing this variable with OUTPUT key word this will be
-- populated inside the Procedure and then you can SELECT it or
-- whatever you want to do with this value.
SELECT #ID
SELECT #value
This should help: Return Data from a Stored Procedure
I think this should work
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
DECLARE #return_value int
DECLARE #media_id uniqueidentifier
--get the value from the stored procedure here
Declare #SQL varchar(max)
set #SQL='INSERT SQL STATEMENT HERE
SELECT #media_id FROM [media] WHERE 1 = 1'
exec #SQL
-- One row affected
RETURN 1
END TRY

How to know TSQL Stored Procedure Update Executed

How can I check if my TSQL stored procedure updated within the stored procedure in order to create a proper message?
Example:
ALTER PROCEDURE [dbo].[pUpdate]
#id uniqueidentifier,
#status int,
#message VARCHAR(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
UPDATE [database].[dbo].[user]
SET status = #status
WHERE Id = #id
END
IF (SUCCESSFUL)
BEGIN
#message = 'Success!'
END
What are some possible ways to check if successful without using the parameters again?
This is what I currently use:
SELECT COUNT(*)
WHERE status = #status AND id = #id
Are there any other ways? I want to know for my knowledge and reference. Thanks.
Have you checked out ##ROWCOUNT? Might be what you're looking for (see this for details: http://technet.microsoft.com/en-us/library/ms187316.aspx). Basically it returns the number of rows affected by the last statement. I'd imagine if it were not "successful", it would be zero rows.
ALTER PROCEDURE [dbo].[pUpdate]
#id uniqueidentifier,
#status int,
#message VARCHAR(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
UPDATE [database].[dbo].[user]
SET status = #status
WHERE Id = #id
END
IF (##ROWCOUNT > 0)
BEGIN
#message = 'Success!'
END
ELSE
BEGIN
#message = 'Not success!'
END
You can use a try catch block and log the success or failure to a table.
BEGIN TRY
BEGIN TRANSACTION
-- Add Your Code Here
-- Log Success to a log table
COMMIT
END TRY
BEGIN CATCH
-- Log failure to a log table
ROLLBACK
END CATCH
I would use ##ERROR system variable to check whether the last sentence was successfull (error # = 0) or not (error # > 0 ):
USE Database;
GO
BEGIN
UPDATE TableName
SET ColumnA = 4
WHERE ColumnB = 1;
END
IF (##ERROR = 0)
BEGIN
PRINT N'Successfull Update';
GO
END
You can go deeper into Microsoft MSDN here: http://technet.microsoft.com/es-es/library/ms188790.aspx
ALTER PROCEDURE [dbo].[pUpdate]
#id uniqueidentifier,
#status int,
#message VARCHAR(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
UPDATE [database].[dbo].[user]
SET status = #status
WHERE Id = #id
END
IF (##ROWCOUNT > 0)
BEGIN
SELECT #message = 'Success!'
END
ELSE
BEGIN
SELECT #message = 'Not success!'
END

Instead of insert trigger SQL

I am trying to create an 'instead of insert trigger' that will not let the name 'john' insert anything into a table. My problem is that even if i change the name to something else, the query is successful but the values arent added.
Any help would be appreciated, thanks in advance.
CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS
Declare #name varchar(50)
Declare #question varchar(50)
Declare #Answer char
Set #name = 'John'
IF (select Username from inserted) = #name
BEGIN
RAISERROR ('You have not paid up your fee', 10,1)
ROLLBACK TRANSACTION
END
ELSE
BEGIN
INSERT INTO question4
values (#name, #question, #Answer)
END
Ok So I have removed your BEGIN and END statements between your IF ELSE statement and wrapped the trigger logic within a BEGIN END
As mentioned in the comments below you dont need the ROLLBACK TRANSACTION
Also you will need to populate #question and #Answer for those to be of any use.
CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS
BEGIN
Declare #name varchar(50)
Declare #question varchar(50)
Declare #Answer char
Set #name = 'John'
IF (select Username from inserted) = #name
RAISERROR ('You have not paid up your fee', 10,1)
--ROLLBACK TRANSACTION
ELSE
INSERT INTO question4
values (#name, #question, #Answer)
END
Hmm, I notice you have declared, but not actually set a value for your variables in your else statement this may have caused SQL to not insert what you expected.
Strangely enough I'm required to do the same in an assignment at the moment, Here's my solution:
CREATE TRIGGER instead_of_insert
ON Question4
INSTEAD OF INSERT AS
Declare #Username varchar(25)
Declare #Question varchar(6)
Declare #Answer char(1)
Set #Username ='John'
IF (Select UserName from inserted) = #UserName
Begin
RAISERROR ('You have not paid up your fee', 10,1)
End
Else
Begin
Set #Username = (Select UserName from inserted)
Set #Question = (Select Question_ID from inserted)
Set #Answer = (Select Answer from inserted)
Insert into User_Responses
Values
(#username, #Question, #Answer)
End

Stored procedure is not working

I have created a stored procedure to retrieve some details based on the certain values passed to a parameter. THis requires switching between the SQLs to be executed by stored procedure. Following is the code:
USE [DFS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[DAFS]
#EmailID Nvarchar(128),
#clientID int,
#userType Varchar(50),
#Success numeric output,
#msg varchar(100) output
AS
BEGIN
if #userType='Normal User'
IF EXISTS (SELECT 1 FROM dbo.Allcdn
WHERE EmailID = #EmailID AND ClientID = #clientID)
begin
set #Success=0
set #msg='Carry on ....'
end
else
begin
set #Success=6
set #msg='Not allowed ...'
END
end
else
Begin
IF EXISTS (SELECT 1 FROM dbo.Alcon
WHERE EmailID = #EmailID AND ClientID = #clientID)
BEGIN
set #Success=0
set #msg='Carry on...'
END
END
End
end
END
The entire processing is based on the variable #userType. Not sure why the stored procedure is not compiling.
Formatting is your friend, just with a quick glance, it appears you have too many ENDs -- See SQL Fiddle with working Demo:
CREATE PROCEDURE [dbo].[DAFS]
#EmailID Nvarchar(128),
#clientID int,
#userType Varchar(50),
#Success numeric output,
#msg varchar(100) output
AS
BEGIN
if #userType='Normal User'
IF EXISTS (SELECT 1 FROM dbo.Allcdn
WHERE EmailID = #EmailID AND ClientID = #clientID)
begin
set #Success=0
set #msg='Carry on ....'
end
else
begin
set #Success=6
set #msg='Not allowed ...'
END
else
Begin
IF EXISTS (SELECT 1 FROM dbo.Alcon
WHERE EmailID = #EmailID AND ClientID = #clientID)
BEGIN
set #Success=0
set #msg='Carry on...'
END
END
end

Resources