I'm tring to create a procedure. And when I set #age after setting #flag, something is wrong. But either I tried to delete set #age or set #flag it would work.
error:there is a syntax error near else
I wonder what caused this. Thanks for help.
select * from sc
if exists(select *
from sysobjects
where name='pro5' and type ='P')
drop procedure pro5
go
create procedure pro5 #stuNo char(10),#flag int output
as
declare #age int
begin
set #age=0
set #flag=1
if exists(select *
from sc
where sno=#stuNo)
set #flag=0
set #age=0
else
delete
from student
where sno=#stuNO
end
return #age
go
declare #flag int
exec pro5 '991102',#flag output
if #flag=1
print 'success'
else
print 'failure'
You need to define a begin and end around all lines in your if statement which by default only assumes a single line belongs to the "if" block:
if exists(select * from sc where sno=#stuNo)
begin
set #flag=0
set #age=0
end
else
delete
from student
where sno=#stuNO
However you could simplify a little since you don't need to also set age which is already 0. I'm assuming you actualy might need to set #age to 1 and this is a cut-down example of your code and you can amend as required:
create procedure pro5 #stuNo char(10), #flag int output
as
declare #age int = 0;
if exists(select * from sc where sno = #stuNo)
set #flag = 0
else
begin
delete from student where sno = #stuNO;
set #flag = 1;
end
return #age;
changed syntax a bit:
create procedure pro5 (
#stuNo char(10),
#flag int output
)
as
begin
declare #age int
set #age=0
set #flag=1
if exists(select *
from sc
where sno=#stuNo)
begin
set #flag=0
set #age=0
end
else
delete
from student
where sno=#stuNO
return #age
end
go
declare #flag int
exec pro5 '991102',#flag output
if #flag=1
print 'success'
else
print 'failure'
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?
This is my stored procedure, this is working:
/*
#CRM_Ref - This is the only required input port for this SP
#North_Ref - Output port, returns the North_Ref for a valid CRM_Ref input
#Output_Message - Output port, Returns the output of the SP, either 'Success' or 'North_Ref not found'
*/
ALTER PROCEDURE [dbo].sp_Get_North_Reference
#CRM_Ref NVARCHAR(255),
#North_Ref VARCHAR(255) OUTPUT,
#Output_Message VARCHAR(255) OUTPUT
AS
DECLARE #var_North_Ref VARCHAR(255); -- Variable used to store the North_Ref
DECLARE #var_Output_Message VARCHAR(255); -- Variable to carry the Output_Message
DECLARE #COUNTER INT; -- Counter for the amount of times the while loop should run
SET #COUNTER = 100;
-- Loop will run 10 times with a 10 second delay between each loop
WHILE #COUNTER >= 1
BEGIN
SET #var_North_Ref = (SELECT TOP 1 North_Ref FROM DEV.dbo.Address__ADDRESS WHERE CRM_Ref = #CRM_Ref ORDER BY PUBLICATION_INSTANCE_DATE DESC)
IF #var_North_Ref IS NULL
BEGIN
SET #COUNTER = #COUNTER - 1; -- Counter is decremented by 1
SET #var_Output_Message = 'North_Ref not found';
WAITFOR DELAY '00:00:10'; -- Wait is triggered if no North_Ref is found
END
ELSE
BEGIN
SET #COUNTER = 0; -- Counter is set to 0 to end the while loop
SET #var_Output_Message = 'Success';
END
END
SET #Output_Message = #var_Output_Message; -- Format Output_Message
SET #North_Ref = #var_North_Ref; -- Format North_Ref
;
GO
I would like to add another parameter into this stored procedure (#TableName VARCHAR(255)) which I want to pass to the SELECT statement.
So I would like something like:
SELECT TOP 1 North_Ref
FROM #Table_Name
WHERE CRM_Ref = #CRM_Ref
ORDER BY PUBLICATION_INSTANCE_DATE DESC
I have tried doing this as it is above but I am getting errors as I don't think you can use parameters as a table name in stored procedures
how about try this concept :
CREATE TABLE #tempTable(abc int);
declare #strSQL nvarchar(255)
SET #strSQL = 'insert into #tempTable select 123'
EXEC sp_executesql #strSQL
declare #abc int
select top 1 #abc = abc from #tempTable
drop table #tempTable
select #abc
ALTER PROCEDURE [dbo].[loginCheck]
#uid AS int ,
#pwd AS nchar(50) ,
#result AS INT OUTPUT
AS
BEGIN
IF EXISTS(SELECT * FROM seller WHERE S_id = #uid AND S_password = #pwd)
BEGIN
SET #result = 1
EXEC(#result)
END
ELSE
BEGIN
SET #result = 0
EXEC(#result)
END
END
This is the code of my stored procedure, I want to check out the id and password when login, so I check if there exists this data in my database.
declare #result int
exec loginCheck 1, '123456', #result output
select #result
I use these to test my stored procedure, but it informed there exist grammatical errors around "1", when i debug by each statement, I found #result has changed to 1, so why i got this error, and how to fix it? Thanks
I am running an SQL procedure that has to update a certain table. When I run the procedure it says successfully completed, yet the records are not updated when I try to debug it, it run only the line SET ANSI ON, then it gives the successful message. I am using SQL server 2012
Am I missing something, is there anything I need to add? See my code here:
USE [CADDe_ProdCopy]
GO
/****** Object: StoredProcedure [dbo].[sp_sms_X203] Script Date: 2015/09/03 08:28:15 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[sp_sms_X203]
as
declare #lCount int
set #lCount = (select count(*) from tbl_X203_SMS where SMSSent = 0 )
if #lCount > 0
begin
DECLARE #cSMSeMail varchar(100)
declare #cSMSType varchar(10)
declare #cSMSSent int
declare #cRA varchar(10)
declare #cWizard varchar(7)
declare #cCName varchar(26)
declare #cContact varchar(30)
declare #cUsed_KM int
declare #cAmount_Due decimal(18, 2)
declare #cSMSMessage varchar(160)
declare #cvblf varchar(1)
declare #cCheckInDt datetime
declare #cCheckOutDt datetime
declare #err int
set #cvblf = '|'
declare lcursor CURSOR FOR
Select SMSType, RA, CName, Contact, Used_KM, Amount_Due, eMail, [CheckInDateTime] ,[CheckOutDateTime]
From tbl_X203_SMS WHERE SMSSent = 0
open lcursor
fetch next from lcursor into #cSMSType, #cRA, #cCName, #cContact, #cUsed_KM, #cAmount_Due, #cSMSeMail, #cCheckInDt, #cCheckOutDt
while ##FETCH_STATUS = 0
begin
--SET #cContact = '+27834115771'
--SET #cSMSeMail = 'amangelsdorf#avis.co.za'
-- Check that the date of the checkin is within same day
if rtrim(ltrim(#cSMSType)) = 'CheckIn'
begin
if datediff(day,#cCheckInDt,getdate()) = 0
begin
SET #cSMSMessage = left('Thank you '+ #cCName +' for renting with AVIS.',160)
SET #cSMSMessage = left( #cSMSMessage + ' RA#' + #cRA + 'Retrieve your invoice at http://www.avis.co.za/inv' ,160)
--if #cAmount_Due > 0
-- SET #cSMSMessage = left( #cSMSMessage + #cvbLf + 'AMT:R ' + cast(#cAmount_Due as varchar),160)
exec sp_sms_xml_post #cContact, #cSMSMessage, #cSMSeMail
end
end
-- Check that the date of the checkout is within same day
if rtrim(ltrim(#cSMSType)) = 'CheckOut'
begin
if datediff(day,#cCheckOutDt,getdate()) = 0
begin
--SET #cSMSMessage = left( 'Thank you for choosing AVIS.' + #cvbLf + 'For any assistance contact the AVIS Careline on Tel: 0800001669' ,160)
SET #cSMSMessage = left( 'Thank you for choosing AVIS. ' + #cvbLf + 'Kindly contact 0800001669 for any roadside or emergency assistance.' ,160)
exec sp_sms_xml_post #cContact, #cSMSMessage, #cSMSeMail
end
end
set #err = ##error
if #err = 0
begin
--print 'no error'
update tbl_X203_SMS set SMSSent = 1 where SMSType = #cSMSType and RA = #cRA
end
fetch next from lcursor into #cSMSType, #cRA, #cCName, #cContact, #cUsed_KM, #cAmount_Due, #cSMSeMail, #cCheckInDt, #cCheckOutDt
end
close lcursor
deallocate lcursor
end
`
You check your count value in
set #lCount = (select count(*) from tbl_X203_SMS where SMSSent = 0 )
if #lCount > 0
because may be you are getting value as 0 so it is not going inside the if condition, you can use print(#lCount ) before if and execute stored procedure from sql server.
The code that you have shown is the code to create / alter a stored procedure and won't execute it, hence the Successfully Compiled response.
In order to execute this procedure you will need to use the exec statement:
exec [dbo].[sp_sms_X203]
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