Condition in a stored procedure - sql

i have a stored procedure that does 2 updates, but i only want to do the first update if the parameter #active is equals to 'Y'.
alter procedure sp_updateThis
#something varchar(5),
#active char(1)
as begin
-- check to see if active and do the update
update myTable set this=#something
-- run this one regardless
update yourTable set that=#something

Try changing that last line with this:
if (#active = 'Y')
begin
update yourTable set that=#something
end

alter procedure sp_updateThis
#something varchar(5),
#active char(1)
as begin
-- check to see if active and do the update
if(#active = 'Y')
Begin
update myTable set this=#something
End
-- run this one regardless
update yourTable set that=#something

If you're really trying to update every row in the table:
update myTable set this=#something where #active = 'Y';
Otherwise you probably want additional clauses there...

you can create a procedure like this:
create procedure sp_updateThis
#something varchar(5),
#active char(1)
AS
Begin
if #active ='y'
begin
update yourTable set that=#something
end
else
update myTable set this=#something
update yourTable set that=#something
end
go

Related

Audit table update trigger does not work using a stored procedure

I have table tblA
Which has a trigger defined on it, if any rows are updated it writes the changes to an audit table.
Now if on SQL Server I right click and edit a row directly, I see changes go to the audit table.
If I call a stored procedure to do an update, I do see tblA updated but the changed values do not go into the audit table. It seems like the trigger does not get fired at all.
What difference is there between directly editing a table or updating through a stored procedurein term of the trigger being fired.
Trigger
USE [dbSuppHousing]
GO
/****** Object: Trigger [dbo].[tblSurvey_trigger] Script Date: 9/22/2015 2:32:51 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* =============================================
Create date: 08/27/15
Description: Trigger to Add audit records to audtSurvey
// =============================================*/
ALTER TRIGGER [dbo].[tblSurvey_trigger] on [dbo].[tblSurvey]
FOR UPDATE,DELETE
AS
SET NOCOUNT ON
Declare #FieldName varchar(100)
, #Deleted varchar(4000)
, #Inserted varchar(4000)
, #SurveyID numeric
, #LoginName varchar(100)
Declare #currentDate datetime = null
SET #currentDate = getdate()
Set #Deleted = ''
Set #Inserted = ''
Select * into #Deleted From Deleted
Select * into #Inserted From Inserted
Create Table #DT ([NameValue] varchar(1000))
Create Table #IT ([NameValue] varchar(1000))
Begin Transaction
Declare auSurveyCur cursor for Select Survey_ID from #Deleted Order By Survey_ID
open auSurveyCur
fetch next from auSurveyCur into #SurveyID
while ##fetch_status = 0
Begin
Declare auU cursor
for Select [name] from syscolumns where id = object_id('dbo.tblSurvey')
open auU
fetch next from auU into #FieldName
while ##fetch_status = 0
Begin
Insert into #DT execute ('Select ' + #FieldName + ' From #Deleted Where Survey_ID = ' + #SurveyID)
Insert into #IT execute ('Select ' + #FieldName + ' From #Inserted Where Survey_ID = ' + #SurveyID)
Set #Deleted = (Select isnull(NameValue,'--') From #DT)
Set #Inserted = (Select isnull(NameValue,'--') From #IT)
If (#Deleted <> #Inserted)
Begin
SELECT #LoginName=Login_Name
From Inserted Where Survey_ID=#SurveyID
if #Deleted = '--' begin set #Deleted = null end
if #Inserted = '--' begin set #Inserted = null end
--#ForWhat=1 means info is for tbSurvey
--In future there may be more tables for auditing and we use same
--Stored procedure to insert audit. Each table has its own audit table.
Execute dbo.InsertauInfo #Surv_ID=#SurveyID
, #auSurveyFieldName=#FieldName
, #auSurveyChangedFrom=#Deleted
, #auSurveyChangedTo=#Inserted
, #auSurveyUpdatedBy=#LoginName
, #auSurveyUpdateDate=#currentDate
, #ForWhat=1
End
Delete From #DT
Delete From #IT
fetch next from auU into #FieldName
End
close auU
deallocate auU
fetch next from auSurveyCur into #SurveyID
END
close auSurveyCur
deallocate auSurveyCur
Commit Transaction
Code for InsertauInfo
ALTER PROCEDURE [dbo].[InsertauInfo]
#Surv_ID bigint,
#auSurveyFieldName varchar(100),
#auSurveyChangedFrom varchar(max),
#auSurveyChangedTo varchar(max),
#auSurveyUpdatedBy varchar(100),
#auSurveyUpdateDate datetime,
#ForWhat int
AS
BEGIN
SET NOCOUNT ON;
IF (#ForWhat=1)
BEGIN
INSERT INTO auSurvey
( Survey_ID
, auSurveyFieldName
, auSurveyChangedFrom
, auSurveyChangedTo
, auSurveyUpdateDate
, auSurveyUpdatedBy
)
VALUES
( #Surv_ID
, #auSurveyFieldName
, #auSurveyChangedFrom
, #auSurveyChangedTo
, #auSurveyUpdateDate
, #auSurveyUpdatedBy
)
END
--ELSE IF (#ForWhat=2)
-- BEGIN
-- INSERT INTO ABC
-- END
END
Example OF stored procedure which does not cause trigger to fire:
OK I'm going crazy but if I Run this very simpple stored procedure directly in DB tirgger gets fired. But if I run from my C# web, Stored procedure will run since tblSurvey gets updated but trigger wont get fired.
ALTER PROCEDURE [dbo].[spUpdateSurveyDataTest]
AS
BEGIN
Update tblSurvey
Set
[s1FirstName]='YES TRIGGER WORKS for sureYES'
Where Survey_Id=327
END
Your trigger only fires on updates and deletes which is why it fired when you edited the table. The stored procedure is performing an insert which is undetected by your trigger. Your trigger should be for INSERT,UPDATE,DELETE.
The point of matter was as I mentioned in the question:
Trigger could not be run from App but I was able to fire it directly from a database update.
The problem was application was connecting to DB with its own generic User which did not have Execute permission for Trigger.
To make things more complicated there was no exception at application level.
The fix was to add
WITH EXECUTE AS OWNER
To the trigger.

Stored procedure unsure syntax

I am trying to create a stored procedure that will determine if my customerid exists if it exists then my other parameter foundcustomer will be assigned to found otherwise not found. I am unsure how to assign found please help
here is what i tried
CREATE PROCEDURE procedure4
-- Add the parameters for the stored procedure here
#FoundCustomer varchar(10) = null,
#Customerid varchar (5) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if Not(#Customerid is null)
SELECT customerid
from customers
where customerid = #Customerid
END
GO
Gordon is right, it sounds like you may want a function but if it has to be a stored procedure you can follow this example.
CREATE PROCEDURE procedure4
#Customerid varchar(5) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FoundCustomer varchar(10) = ''
IF #FoundCustomer is not null
BEGIN
IF (SELECT COUNT(1) FROM customers WHERE customerid = #customerid) > 0
SET #FoundCustomer = 'Found'
ELSE
SET #FoundCustomer = 'Not Found'
END
SELECT #FoundCustomer
END

Return one OUTPUT result from MERGE query

I have a merge query which updates or inserts if no records found. In my results, I have a problem when the record does not exist and it get inserted. The query returns BOTH 'Updated' (as empty) and 'Inserted' (with the proper value).
Any ideas how to avoid return the empty 'Updated' when there are no updates?
ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
-- Add the parameters for the stored procedure here
#Name nvarchar(50),
#Surname nvarchar(50),
#Position nvarchar(50),
#NationalID int,
#ApplicantID int
AS
BEGIN
SET NOCOUNT ON;
-- Update the row if it exists.
UPDATE tbApplicant
SET Name = #Name, Surname = #Surname, Position = #Position, NationalID = #NationalID
OUTPUT INSERTED.ApplicantID AS 'Result'
WHERE ApplicantID = #ApplicantID;
-- Insert the row if the UPDATE statement failed.
IF (##ROWCOUNT = 0 )
BEGIN
INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
OUTPUT INSERTED.ApplicantID AS 'Result'
VALUES (#Name, #Surname, #Position, #NationalID)
END
END;
It seems that the 'output' always fires even if no actual rows were updated. You can see the same behavior in triggers. You might want to consider doing the following:
ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
-- Add the parameters for the stored procedure here
#Name nvarchar(50),
#Surname nvarchar(50),
#Position nvarchar(50),
#NationalID int,
#ApplicantID int
AS
BEGIN
SET NOCOUNT ON;
-- Check if the row exists.
IF EXISTS (SELECT 1 FROM tbApplicant WHERE ApplicantID = #ApplicantID) BEGIN
-- update if the row exists.
UPDATE tbApplicant
SET Name = #Name, Surname = #Surname, Position = #Position, NationalID = #NationalID
OUTPUT INSERTED.ApplicantID AS 'Result'
WHERE ApplicantID = #ApplicantID;
END
ELSE BEGIN
-- Else Insert.
INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
OUTPUT INSERTED.ApplicantID AS 'Result'
VALUES (#Name, #Surname, #Position, #NationalID)
END
END;
I do something very similar.
Inside my stored procedure, I have this:
DECLARE #mergeResults TABLE (mergeAction varchar(10), tableName varchar(50));
OUTPUT $action, 'Table Name' INTO #mergeResults;
Can you insert into the table variable and then decide how you want to move the data based on what you see?
You mentioned you have a merge query but you aren't using a merge - you're using more of an "upsert".
Merge T-SQL: http://msdn.microsoft.com/en-us/library/bb510625.aspx

trigger at particular column with condition

I want to check a Column value when update.If its match insert into another table.
My Tables:
My trigger:
CREATE TRIGGER tr_test
ON test1
FOR UPDATE
AS
SET nocount ON
IF ( Update(sname) )
DECLARE #Name NVARCHAR
DECLARE #id INT
SET #id=##IDENTITY
SET #Name=(SELECT sname
FROM test1
WHERE id = #id)
IF( #Name = 'Paras' )
BEGIN
INSERT INTO test2
(loginfo)
VALUES ('success')
END
And my update query is:
update Test1 set Sname='Paras' where ID=1
When I run this update query Nothing is happen.Test2 table is empty.I think problem is ##IDENTITY but not sure.Thanks.
Try this:
CREATE TRIGGER tr_test
ON test1
FOR UPDATE
AS
SET nocount ON
IF ( Update(sname) )
DECLARE #Name NVARCHAR
DECLARE #id INT
SET #id=(select id from inserted)
SET #Name=(SELECT sname
FROM inserted
WHERE id = #id)
IF( #Name = 'Paras' )
BEGIN
INSERT INTO test2
(loginfo)
VALUES ('success')
END
But it's better to do this, an update can update many rows, the above will fail if UPDATE matches many rows, use EXISTS:
CREATE TRIGGER tr_test
ON test1
FOR UPDATE
AS
SET nocount ON
IF( EXISTS(select * From inserted where sname = 'Paras' ) )
BEGIN
INSERT INTO test2
(loginfo)
VALUES ('success')
END
inserted table is the name of the table where the UPDATE's new values goes, deleted table is the name of the table where UPDATE's old values goes

Stored Procedure OutPut Parameters

i need to write a stored procedure which will return a string.logic is
when user try to insert a new record i need to check whether that record already exist.if exist need to return msg "Record exist" else return "Inserted"
following is what i have done for the moment and i'm stuck here.can some one help me to complete the procedure
CREATE PROCEDURE [dbo].[spInsetPurpose]
#Purpose VARCHAR(500),
#Type VARCHAR(6),
#Result VARCHAR(10)= NULL OUTPUT
AS
BEGIN
Declare #Position VARCHAR(20)
DECLARE #TempTable TABLE (Purpose VARCHAR(500))
INSERT INTO #TempTable
SELECT Purpose FROM tblPurpose WHERE Purpose=#Purpose
INSERT INTO tblPurpose(Purpose,[Type]) VALUES(#Purpose,#Type)
END
To check if the row already exists you can do
If Exists (Select Top 1 1 from tblPurpose where Purpose = #Purpose and [Type] = #Type)
Begin
Insert Into tblPurpose
(Purpose, [Type])
Select
#Purpose, #Type
SET #Result = 'Inserted'
End
Else
Begin
SET #Result = 'Record exists'
End