SQL Server stored procedure compile error - sql

Stored procedure is:
CREATE PROCEDURE CountUtily
#domain varchar(50),
#count int,
#totalCount int OUT
AS
BEGIN
SET NOCOUNT ON
SET #totalCount=0
IF (EXISTS (SELECT #totalCount = count
FROM FormFillerAuto2_DomainCount
WHERE domain = #domain))
BEGIN
SET #totalCount = #totalCount + #count
UPDATE FormFillerAuto2_DomainCount
SET count = #totalCount
WHERE domain = #domain
END
ELSE
BEGIN
INSERT INTO FormFillerAuto2_DomainCount (domain, count)
VALUES (#domain, #count)
END
END
Error:
Incorrect syntax near '='. Incorrect syntax near the keyword 'ELSE'.

your Select #totalCount = count does not return a bool. Try setting #totalCount before the if evaluates and eval the count in the if
CREATE PROCEDURE CountUtily
#domain varchar(50),
#count int,
#totalCount int OUT
AS BEGIN
SET NOCOUNT ON
SET #totalCount=0
SELECT #totalCount=count FROM FormFillerAuto2_DomainCount WHERE
IF (#totalCount > 0)
begin
SET #totalCount=#totalCount+#count
UPDATE FormFillerAuto2_DomainCount SET count=#totalCount WHERE domain=#domain
end
ELSE
begin
INSERT INTO FormFillerAuto2_DomainCount (domain, count) VALUES (#domain, #count)
end
end

See EXISTS
Specifies a subquery to test for the existence of rows. it Returns
TRUE if a subquery contains any rows,it accept restricted SELECT statement, The INTO keyword is not allowed.
the problem here is you can't set the value inside the Exists.
Try
alter PROCEDURE CountUtily
#domain varchar(50),
#count int,
#totalCount int OUT
AS BEGIN
SET NOCOUNT ON
SET #totalCount=0;
IF (EXISTS (SELECT [count] FROM FormFillerAuto2_DomainCount WHERE domain=#domain))
begin
SELECT #totalCount=[count] FROM FormFillerAuto2_DomainCount WHERE domain=#domain
UPDATE FormFillerAuto2_DomainCount SET count=#totalCount WHERE domain=#domain
end
ELSE
begin
INSERT INTO FormFillerAuto2_DomainCount (domain, count) VALUES (#domain, #count)
end
end

I believe you are missing ; to mark the end of the statement here. Again, count is a reserve word and so escape it using []. Your posted procedure can be modified to
CREATE PROCEDURE CountUtily(
#domain varchar(50),
#count int,
#totalCount int OUT)
AS BEGIN
SET NOCOUNT ON;
SET #totalCount=0;
SELECT #totalCount=[count] FROM FormFillerAuto2_DomainCount WHERE domain=#domain;
IF (#totalCount IS NOT NULL)
begin
SET #totalCount=#totalCount+#count;
UPDATE FormFillerAuto2_DomainCount SET [count]=#totalCount WHERE domain=#domain;
end
ELSE
INSERT INTO FormFillerAuto2_DomainCount (domain, [count]) VALUES (#domain, #count);
end

You've made this query too complicated with the count and totalcount variables; all of which you do not need.
So, you want to update the "count" field of your "FormFillerAuto2_DomainCount" when the field "domain" matches a parameter #domain; or you want to Insert it if it doesn't exist.
OK, let's do that using ##RowCount.
UPDATE FormFillerAuto2_DomainCount SET [count] = ([count]+#count) where [domain] = #domain
If (##ROWCOUNT > 0)
BEGIN
return 1 --updated : or return whatever you need to show it updated
END
ELSE
BEGIN
INSERT INTO FormFillerAuto2_DomainCount ([domain], [count]) VALUES (#domain, #count)
return 2 --inserted : or return whatever you need to show it inserted
END

It seems like your update is a bit screw up.. It should be
UPDATE TABLENAME
SET COLUMNNAME = VALUE
WHERE CONDITION
Readability will help understand and maintain code.

Related

Updating Null records of a table by invoking stored procedure throws error 'Subquery returned more than one value'

I am trying to update all null values of a column with Uuid (generated with the help of a stored procedure GetOptimizedUuid). While doing so I am getting an error
Subquery returned more than 1 value
I could understand the causes of error but none of my fix helped out.
I tried out with some loops but it doesn't fix
BEGIN
DECLARE #no INT;
DECLARE #i INT;
SET #no = (SELECT COUNT(id) FROM table1)
SET #i = 0;
WHILE #i < #no
BEGIN
DECLARE #TempUuid TABLE(SeqUuid UNIQUEIDENTIFIER, OptimizedUuid UNIQUEIDENTIFIER)
INSERT INTO #TempUuid
EXECUTE [Sample].[dbo].[GetOptimizedUuid]
UPDATE table1
SET col2 = (SELECT OptimizedUuid FROM #TempUuid)
WHERE col2 IS NULL;
SET #i = #i + 1;
END
END
Help me to sort out this, Thanks!
Not entirely sure what you're doing - what do you need to call this GetOptimizedUuid stored procedure? Can't you just use NEWID() to get a new GUID?
Anyway - assuming you have to call this stored procedure, I assume you'd call it once before the loop, to get the ID's you need - and then you get the top (1) UUID from the table and update one row in your database table - and then you also need to remove that UUID that you've just used from the temp table, otherwise you keep re-using the same ID over and over again....
Try something like this:
BEGIN
DECLARE #no INT;
DECLARE #i INT;
SET #no = (SELECT COUNT(id) FROM table1)
SET #i = 0;
-- define and fill the table *ONCE* and *BEFORE* the loop
DECLARE #TempUuid TABLE(SeqUuid UNIQUEIDENTIFIER, OptimizedUuid UNIQUEIDENTIFIER)
INSERT INTO #TempUuid
EXECUTE [Sample].[dbo].[GetOptimizedUuid]
-- declare a UUID to use
DECLARE #NewUuid UNIQUEIDENTIFIER;
WHILE #i < #no
BEGIN
-- get the first UUID from the temp table
SELECT TOP (1) #NewUuid = OptimizedUuid
FROM #TempUuid;
-- update your table
UPDATE table1
SET col2 = #NewUuid
WHERE col2 IS NULL;
-- *REMOVE* that UUID that you've used from the table
DELETE FROM #TempUuid
WHERE OptimizedUuid = #NewUuid;
SET #i = #i + 1;
END
END

Creating an Instead of insert Trigger SQL

I am a DBA with my company. I am trying to create trigger that will check any insert statement for duplicates first then if none allow the original insert. Not even sure this can be done. The insert statements may be written by various users so the statements will never be the same. All I have found so far is the check for duplicates but the insert statement is then hard coded in the trigger. My plan is also to check update as well, but it is not important right now.
Here is my current code.
ALTER TRIGGER [dbo].[BlockDuplicatesOnTable]
ON [dbo].[blockduplicates]
Instead of INSERT, Update
AS
BEGIN
SET NOCOUNT ON;
Declare #ProviderAcctNumber nvarchar(50)
Declare #Referredby int
Declare #Action as char(1)
Declare #Count as int
Set #Action = 'I'
Select #Count = Count(*) from DELETED
IF #Count > 0
Begin
Set #Action = 'D'
Select #Count = count(*) from INSERTED
IF #Count > 0
Set #Action = 'U'
IF #Action = 'I'
Begin
IF not exists (Select 1 from inserted as i
inner join dbo.blockduplicates as b
on i.ProviderAcctNumber = b.ProviderAcctNumber
and i.Referredby = b.Referredby)
Begin
--execute original insert
End
Else
Begin
Print 'Duplicate insert'
Raiserror ('Duplicate Entry for Insert',16,1);
Return
End
End
Else IF #Action = 'U'
Begin
Select #ProviderAcctNumber = ProviderAcctNumber, #Referredby = Referredby from inserted
IF Not exists (Select 1 from deleted where ProviderAcctNumber = #ProviderAcctNumber and Referredby = #Referredby)
Begin
Print 'Update Statement is True';
End
Else
Begin
Print 'duplicate'
Raiserror ('Duplicate Entry for Update',16,1);
Return
End
End
End
End;

How to update SQL field using function and stored procedure?

What I want to do is to update column (NewID) in my table (SampleTable) with the following code, but it's not working.. can somebody help me please? Whats wrong with it?
I have the table 'SampleTable' wich has the fields 'NewID' and 'OldID'.
UPDATE SampleTable SET NewID = dbo.fn_DoStuff(OldID) <-- Not working
My function:
ALTER FUNCTION [dbo].[fn_DoStuff]
(
#int oldid
)
RETURNS int
AS
BEGIN
DECLARE #returnValue int
EXEC #returnValue = dbo.spc_DoStuff #oldid
RETURN #returnValue
END
My stored procedure:
SampleTable1 has the columns ID, SomeColName.
ALTER PROCEDURE [dbo].[spc_GeraAtriðisorðalistaÚrAtriðisorði]
(
#oldid int
)
AS
BEGIN
DECLARE #returnValue int
INSERT INTO SampleTable1 (SomeColName) VALUES (null)
SET #returnValue = ##IDENTITY
INSERT INTO SampleTable2 (SomeColName1, SomeColName2) VALUES (#returnValue, #oldid)
SELECT #returnValue AS RetVal
END
You have 2 problems, the first is you cannot call a stored procedure inside a function, nor can you perform your insert within a function.
The second problem is that even if you could call a stored procedure inside a function, you are not returning the value from the procedure correctly. You would need something like:
CREATE TABLE dbo.T (ID INT IDENTITY, Filler CHAR(10));
GO
CREATE PROCEDURE dbo.Test
AS
DECLARE #i INT;
INSERT dbo.T (Filler) VALUES (NULL);
RETURN SCOPE_IDENTITY();
GO
Note the use of the RETURN statement, if you don't use this the default return value is 0
Then you can use:
DECLARE #i INT;
EXECUTE #i = dbo.Test;
SELECT ReturnVal = #i;
*Note, I have replaced ##IDENTITY with SCOPE_IDENTITY(), ##IDENTITY is rarely the correct function to use*
Example on SQL Fiddle
With your solution GarethD I could still not call the function like I wanted to
UPDATE SampleTable SET NewID = dbo.fn_DoStuff(OldID).
Your code helped me though to start thinking another way. Now I'm using a cursor and a while loop and it works perfectly. See my solution below:
DECLARE #OldID AS INT
DECLARE Upd_CURSOR FOR
SELECT OldID
FROM dbo.SampleTable
WHERE OldID is not null
FOR UPDATE OF NewID
OPEN Upd_CURSOR;
FETCH NEXT FROM Upd_CURSOR INTO #OldID
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #returnValue int;
INSERT INTO SampleTable1 (SomeColName) VALUES (null);
SET #returnValue = SCOPE_IDENTITY();
INSERT INTO SampleTable2 (SomeColName1, SomeColName2) VALUES (#returnValue, #OldID)
UPDATE dbo.SampleTable SET NewID = #returnValue WHERE CURRENT OF Upd_CURSOR;
FETCH NEXT FROM Upd_CURSOR INTO #OldID;
END;
CLOSE Upd_CURSOR;
DEALLOCATE Upd_CURSOR;
GO

Yet another primary key exception

Last year I ask this question: What could be causing the primary key exception?
But I still have another error in this stored procedure: randomly I get
INSERT EXCEPTION WITH FOREIGN KEY "FK_Sessions" WITH TABLE
"Sessions", column "id".
CREATE PROCEDURE [dbo].[MyProcedure]
#sessionId varchar(512),
#variable varchar(350),
#value image
AS
BEGIN
BEGIN TRAN
DECLARE #result int = 0;
DECLARE #locked bit;
IF (SELECT COUNT(*) FROM Sessions WITH(ROWLOCK,HOLDLOCK) WHERE id = #sessionId) = 0
BEGIN
SET #result = -1;
END
ELSE BEGIN
DELETE Variables WITH(ROWLOCK,HOLDLOCK) WHERE sessionId = #sessionId AND variable = #variable
IF #value IS NOT NULL
BEGIN
INSERT Variables VALUES(#sessionId, #variable, #value, 0)
END
END
COMMIT TRAN
RETURN #result
END
Any ideas? Thanks again

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