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
Related
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?
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.
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
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
I have a stored procedure named insert2Newsletter with parameters
(#sex nvarchar(10),
#f_name nvarchar(50),
#l_name nvarchar(70),
#email nvarchar(75),
#ip_address nvarchar(50),
#hotelID int,
#maArt nchar(2))
I want call this stored procedure in an insert trigger. How do I retrieve the corresponding fields from inserted and how do i call insert2Newsletter within the trigger?
I tried without success:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER RA2Newsletter
ON [dbo].[Reiseagent]
AFTER INSERT
AS
DECLARE #rAgent_Name nvarchar(50),
DECLARE #rAgent_Email nvarchar(50),
DECLARE #rAgent_IP nvarchar(50),
DECLARE #hotelID int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select #rAgent_Name=rAgent_Name, #rAgent_Email=rAgent_Email, #rAgent_IP=rAgent_IP, #hotelID=hotelID From Inserted
EXEC insert2Newsletter '','',#rAgent_Name,#rAgent_Email,rAgent_IP,#hotelID,'RA'
END
GO
thx a lot for your feedback... greetings...
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE #rAgent_ID INT = 0
-- Looping variable.
DECLARE #i INT = 0
-- Count of rows affected for looping over
DECLARE #count INT
-- These are your old variables.
DECLARE #rAgent_Name NVARCHAR(50)
DECLARE #rAgent_Email NVARCHAR(50)
DECLARE #rAgent_IP NVARCHAR(50)
DECLARE #hotelID INT
DECLARE #retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT #Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE #i < #count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
#rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > #rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT #rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = #rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', #rAgent_Name, #rAgent_Email,
#rAgent_IP, #hotelID, 'RA', #retval
-- Set up next iteration
SET #i = #i + 1
END
END
GO
I sure hope this helps you out. Cheers!
Finally ...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[RA2Newsletter]
ON [dbo].[Reiseagent]
AFTER INSERT
AS
declare
#rAgent_Name nvarchar(50),
#rAgent_Email nvarchar(50),
#rAgent_IP nvarchar(50),
#hotelID int,
#retval int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select
#rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
From Inserted
EXEC insert2Newsletter
'',
'',
#rAgent_Name,
#rAgent_Email,
#rAgent_IP,
#hotelID,
'RA',
#retval
END
The following should do the trick - Only SqlServer
Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN
SET NOCOUNT ON;
Declare #id int
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
select #id=deleted.Catagory_id from deleted
print #cDate
execute dbo.psp_Update_Category #id
END
Alter PROCEDURE dbo.psp_Update_Category
#id int
AS
BEGIN
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
--Update Catagory_Master Set Modify_date=''+#cDate+'' Where Catagory_ID=#id --#UserID
Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END
You pass an undefined rAgent_IP parameter in EXEC instead of the local variable #rAgent_IP.
Still, this trigger will fail if you perform a multi-record INSERT statement.