How to know TSQL Stored Procedure Update Executed - sql-server

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

Related

Get value from store or store and get if not exists

what I want to achieve is a way to get previously generated or generate, store and return data, in a way, which could be used as function - needed to join or APPLY in UPDATE scripts.
So, having data generate function:
ALTER FUNCTION generateData()
RETURNS NVARCHAR(20)
AS
BEGIN
RETURN 'asdyukyuk' --some rng related algorithm
END
And "get or generate, save and get" procedure:
ALTER PROCEDURE getOrGenerateAndGet (#orig NVARCHAR(20), #result NVARCHAR(20) OUTPUT)
AS
BEGIN
IF #orig IS NULL
BEGIN
SET #result = NULL
END
ELSE
BEGIN
DECLARE #hash VARBINARY(64) = dbo.getHash(#orig)
SELECT #result = GENERATED_DATA FROM STORED_DATA WHERE HASH = #hash
IF #result IS NULL
BEGIN
SET #result = dbo.generateData()
INSERT INTO STORED_DATA (HASH, GENERATED_DATA) VALUES (#hash, #result)
END
END
RETURN 1
END;
GO
And UPDATE script:
UPDATE FRAGILE_DATA SET FRAGILE_COLUMN = getOrGenerateAndGet(FRAGILE_COLUMN)
it's obviously not working, because getOrGenerateAndGet is not function.
However, with function way:
CREATE FUNCTION getOrGenerateAndGet (#orig NVARCHAR(20))
RETURNS NVARCHAR(20)
AS
BEGIN
DECLARE #result NVARCHAR(20)
IF #orig IS NULL
BEGIN
SET #result = NULL
END
ELSE
BEGIN
DECLARE #hash VARBINARY(64) = dbo.getHash(#orig)
SELECT #result = GENERATED_DATA FROM STORED_DATA WHERE HASH = #hash
IF #result IS NULL
BEGIN
SELECT #result = dbo.generateData()
EXEC sp_executesql N'INSERT INTO STORED_DATA (HASH, GENERATED_DATA) VALUES (#hash, #result)'
END
END
RETURN #result
END;
GO
it's still not working, because "Only functions and some extended stored procedures can be executed from within a function."
Is there any way to achieve this, without enabling sql command shell?

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.

If else doesn't work in stored procedures

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.

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

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