Incorrect syntax near 'BEGIN'. in TSQL - sql-server

hello programmers i'm writing a TSQL in-line table function, actually im not good enough in sql, when i finished my code i've got this error "Incorrect syntax near 'BEGIN'." , anyone know the solution please give it to me.
by the way when i clicked double-click over the error msg it's selected the last "end"
create FUNCTION [dbo].[CheckLogin]
(
#un varchar(max),
#pw varchar(max)
)
RETURNS TABLE
AS
begin
declare #unexist int, #unpwmatch int, #uid bigint
declare #uisactivated bit , #uisdeleted bit
-----
set #unexist = (select COUNT(UserAccessInfo.UserId) FROM UsersAccessInfo
WHERE UserAccessInfo.UserName = #un OR UserAccessInfo.UserEmail = #un)
------
set #unpwmatch = (select count(usersaccessinfo.userid) from usersaccesinfo
WHERE (usersaccessinfo.UserName = #un) AND (usersaccessinfo.UserPassword = #pw) OR
(usersaccessinfo.UserEmail = #un) AND (usersaccessinfo.UserPassword = #pw))
------
set #uid =(select usersaccessinfo.userid from usersaccessinfo where
serAccessInfo.UserName = #un OR UserAccessInfo.UserEmail = #un)
------
if #uid <> Null
begin
set #uisactivated =(select usersaccessinfo.userisactivated from usersaccessinfo
where usersaccessinfo.userid=#uid)
end
------
if #uid <> null
begin
set #uisactivated =(select usersaccessinfo.userisactivated from usersaccessinfo
where usersaccessinfo.userid=#uid)
end
------
if #unexist = 0
begin
select dbo.getreportbyid('1004')
end;
else if #unpwmatch = 0
begin
select dbo.getreportbyid('1005')
end;
else if #uid<>0
begin
if #uisactivated =0
begin
select dbo.getreportbyid('1002')
end;
else if #uisdeleted = 1
begin
select dbo.getreportbyid('1003')
end;
end;
else
begin
select ('successful') as report
end;
return
end;

The problem is these lines:
...
RETURNS TABLE
AS
...
This is not valid syntax for any of the four types of user-defined functions.
Assuming that you are trying to define a multi-statement table-valued function, it should look like this:
...
RETURNS #YourTableName TABLE( <column-definitions>... )
AS
...
And then your function statements should be putting the function return data into that table before it executes the RETURN statement, which it also is not doing.

Your problem is that you are mixing the syntax of multi-statement table valued functions and inline table valued functions. For examples of each and some performance considerations check out my post here: http://sqlity.net/en/498/t-sql-tuesday-24-prox-n-funx/
In short, if you want to use multiple statements within a table valued function you have to declare a table variable after the RETURNS keyword and insert the rows you want to return in there in the function body. However, this type of function has serious performance implications and you should try hard to stay away from it.
Besides of that, you seem to have mismatching BEGINs and ENDs. As Barry said, "A little indentation would go a long way here" in helping you and others understand you code better.

You cannot have ; before the if command end. Also null checing is wrong. For ex;
if #uid <> null -- (1) note: should be if #uid is not null
Begin
-- query
End; --(2)-Note: this is wrong
Else
Begin
--Query
End

Related

SqlException: Procedure or function expects parameter which was not supplied SSMS

I am sure the solution is something super simple that I am missing but I keep getting a
SqlException: Procedure or function expects parameter which was not supplied
error. I am not a SQL wizard but to me the parameter looks okay. I did change the parameter and was not receiving this error but then when I consistently started receiving it I restored the stored procedure to the original version that I knew for a fact was fine but still receive it.
I tried executing the stored procedure like this
EXECUTE [dbo].[BHS_CloseCnt_Print_PackList] #palletid = '562992'
with a variable filled in. This stored procedure calls a function that determines the status of an order, if the variable I plug in and check with this method meets the criteria for the function I get an expected return.
If the container does not yet meet the function criteria, I get a null which I believe is okay.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[BHS_CloseCnt_Print_PackList]
(#PalletId numeric)
AS
BEGIN
Declare #PO as nvarchar(50)
Declare #Internal_Shipment_Num as numeric
Declare #Internal_Shipment_Line_Num as numeric
select top 1
#Internal_Shipment_Num = sc.INTERNAL_SHIPMENT_NUM,
#Internal_Shipment_Line_Num = sc.INTERNAL_SHIPMENT_LINE_NUM
from
SHIPPING_CONTAINER sc
where
INTERNAL_CONTAINER_NUM = #PalletId
or PARENT = #PalletId
and INTERNAL_SHIPMENT_LINE_NUM is not null
select #PO = dbo.fn_BHS_AllPOPLTS_CLOSED(#PalletId, #Internal_Shipment_Num, #Internal_Shipment_Line_Num)
print #PO
if #PO is not null
Begin
select #PalletId 'INTERNAL_CONTAINER_NUM', '60' 'DOCUMENT_TYPE'
End
End
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_BHS_AllPOPLTS_CLOSED]
(#palletId numeric,
#Internal_Shipment_Num numeric,
#Internal_Shipment_Line_Num numeric)
RETURNS nvarchar(50)
AS
BEGIN
Declare #PO nvarchar(50)
Declare #OPENPO nvarchar(50)
Declare #IntShip as numeric
select #PO = isnull(sd.CUSTOMER_PO, 'FEIT')
from SHIPMENT_DETAIL sd
where sd.INTERNAL_SHIPMENT_LINE_NUM = #Internal_Shipment_Line_Num
and sd.internal_shipment_num = #Internal_Shipment_Num
select #OPENPO = isnull(sd.CUSTOMER_PO, '')
from shipping_container sc
join SHIPMENT_DETAIL sd on sd.INTERNAL_SHIPMENT_LINE_NUM = sc.INTERNAL_SHIPMENT_LINE_NUM
where sd.CUSTOMER_PO = #PO and sc.INTERNAL_SHIPMENT_NUM = #Internal_Shipment_Num
and sc.status < 600
if(isnull(#OPENPO, '') != '')
Begin
set #PO = null
End
return #PO
End
The stored procedure looks to have stored the cache from the previous edit I did although a known working version was restored.
Resolution for this was to run DBCC FREEPROCCACHE to clear the stored procedure cache and I was able to execute as expected.
Thanks Nemanja Perovic!

Incorrect syntax near begin in sql server while creating function

I am stuck with a very petty issue that I am unable to resolve.
CREATE FUNCTION dbo.fntblPsmHaendlerDailyCostsinfodump(#pDateString varchar(8), #HaendlerID int, #TableName varchar(100),#CountryID int)
RETURNS table
AS BEGIN
RETURN select top 10 * from tblcountry
END
GO
This is giving me an error -
'Incorrect syntax near begin'.
I am not able to identify why it is giving the error.
Correct syntax for inline UDF:
Inline user-defined functions follow these rules:
There is no function_body delimited by BEGIN and END.
The RETURN clause contains a single SELECT statement in parentheses.
CREATE FUNCTION dbo.fntblPsmHaendlerDailyCostsinfodump(
#pDateString varchar(8),
#HaendlerID int,
#TableName varchar(100),
#CountryID int)
RETURNS table
AS
RETURN (select top 10 * from tblcountry);
GO
BEGIN and END are necessary for multistatement UDFs.

Check if there are any records in a table which may not exist

I have to check if some records with specific conditions exist in a table which may not exist and I must do this in a scalar function.
Here is my code:
CREATE FUNCTION CheckIfRecordsExistInTestTable()
RETURNS INT
BEGIN
DECLARE #Result INT
SELECT #Result =
CASE WHEN OBJECT_ID('TestTable') IS NULL THEN 0
ELSE
CASE WHEN EXISTS(SELECT * FROM TestTable) THEN
1
ELSE
0
END
END
RETURN #Result
END
While trying it in SQL Server executing the following statement:
SELECT dbo.CheckIfRecordsExistInTestTable()
Whenever TestTable exists it returns my expected result. But whenever it does not, SQL Server raises an exception (Invalid object name 'TestTable') and I cannot get what I expect (I want a zero return value in this situation).
So what do you propose to do for this problem which can be coded to a scalar function?
The other answer gives a correct workaround.
As to why you are getting the problem...
This is a compile time error.
If the statement references a non existent object compilation is deferred until just before execution, but still eventually the whole statement needs to be compiled into an execution plan before it is executed.
This fails when the table doesn't exist and execution of that statement doesn't even begin.
(Execution plan that it tries to create - using a passthru predicate to avoid evaluation of the condition if the CASE not met)
In the workaround the SELECT against testtable is moved into a different statement. Compilation of this statement is still deferred and as the statement is never executed all works fine.
Try changing the function like this
CREATE FUNCTION Checkifrecordsexistintesttable()
returns INT
BEGIN
DECLARE #Result INT
IF Object_id('TestTable') IS NULL
SET #Result = 0
ELSE
SELECT #Result = CASE
WHEN EXISTS(SELECT 1 FROM testtable) THEN 1
ELSE 0
END
RETURN #Result
END;
To know more about the reason behind the error you are getting check Martin's answer.
update function like this:
CREATE FUNCTION CheckIfRecordsExistInTestTable()
RETURNS INT
BEGIN
DECLARE #Result INT
SELECT #Result = case when count(1) = 0 then 0 else 1 end from sys.tables where name = 'TestTable'
RETURN #result
END

must declare scalar variable error in Powerbuilder

I'm facing this error " must declare the scalar variable #return " in PowerBuilder 9 running on SQL server 14. When I'm executing the stored procedure using the SQL management studio it is returning 10000 as expected. But while calling this SP from PowerBuilder I'm facing the error. Any suggestions are appreciated. Thanks
Function in PowerBuilder code:
Declare sp_v procedure for
#return = proc_v_sp
#eid = :p_eid,
#year = :p_year,
#bid = :p_bid,
#hid = :p_hid
using sqlca;
Execute sp_v;
IF SQLCA.SQLCode <> 0 THEN
lReturn = SQLCA.SQLCode
ELSE
FETCH sp_v INTO :lReturn;
END IF
CLOSE sp_v;
In SQL SERVER SP:
Alter procedure proc_v_sp
#eid int,
#year int,
#bid varchar(8),
#hid char(3)
As
Begin
Declare #count int,
Declare..............
..........ignoring as it is long SP...........
Select #count = count(*)
from sy_e
where sy_e_eid = #eid and sy_e_year= #year
IF #count >0
RETURN 20000
ELSE
RETURN 10000
END
Looking at the documentation, I don't see anything about how to get a RETURN value back from an executed stored procedure. The documentation lists the syntax for the SP declaration in PB as...
DECLARE logical_procedure_name PROCEDURE FOR
SQL_Server_procedure_name
#Param1 = value1, #Param2 = value2,
#Param3 = value3 OUTPUT,
{USING transaction_object} ;
So that's why you're getting the syntax error. It's just not expecting #return there. If you can change the stored procedure, then you should be able to use an OUTPUT parameter. After a bit of googling, it looks like you would still have to use FETCH after the EXECUTE to get the variable specified for the output parameter populated.
I came back to this once I had PB in front of me because I was curious if it was possibles. After a bit of experimentation and looking at the MSDN docs for RETURN, I was able to get the return value populated in the returnValue variable using the code below.
long returnValue
DECLARE sp_test PROCEDURE FOR
#return_status = sp_test_return
USING SQLCA;
EXECUTE sp_test;
FETCH sp_test INTO :returnValue;
Here's the stored procedure.
CREATE PROCEDURE [dbo].[sp_test_return]
AS
RETURN 159
GO
You're making this all way too hard...
Change your RETURN to SELECT, and use a stored procedure datawindow. You can then rip out all that code, and replace it with one line.
dw.retrieve( args )
And your return value will be dw.getItemNumber( 1, "return_status")
-Paul-
I don't have sample code.
But it's super easy... Your SP needs to return a result set instead of a return value - even if that result set is a single value on a single row.
Change the RETURN to SELECT. That returns a result set.
Now, create a datawindow and select Stored Procedure as the datasource. Then select your sp as the source. Test it by providing the values for arguments and seeing if it returns the result you're looking for.
From here, it's just PB code.
datastore myDW
myDW = create datastore
myDW.setTransObject( SQLCA )
myDW.retrieve( args... )
theResult = myDW.getItemNumber( 1, "return_status" )

SQL Server : Query not running as needed

I am working with Sage Evolution and do a lot of the back end stuff to customize it for our company.
I need to write a query where, when a user enters a negative quantity the system must not allow the transaction, however when the user enters a negative quantity and the product belongs to the "chemicals" group it needs to process the transaction.
Here is my code I have written so far.
DECLARE
#iAfterfQuantity Int;
#iAfteriStockCodeID Int;
#iAfterStockItemGroup VarChar
SELECT
#iAfterfQuantity = fQuantity,
#iAfteriStockCodeID = iStockCodeID
FROM
INSERTED
SELECT
#iAfterStockItemGroup = ItemGroup
FROM
dbo.stkItem
WHERE
StockLink = #iAfteriStockCodeID
BEGIN
IF #iAfterfQuantity < 0 AND #iAfterStockItemGroup <> 'chemicals'
BEGIN
RAISERROR ('',16,1)
ROLLBACK TRANSACTION
END
END
This is a task better suited for a check constraint then for a trigger, especially considering the fact that you are raising an error.
First, create the check function:
CREATE FUNCTION fn_FunctionName
(
#iAfterfQuantity Int,
#iAfteriStockCodeID Int
)
RETURNS bit
AS
BEGIN
DECLARE #iAfterStockItemGroup VarChar(150) -- Must specify length!
SELECT #iAfterStockItemGroup = ItemGroup FROM dbo.stkItem WHERE StockLink=#iAfteriStockCodeID
IF #iAfterfQuantity < 0 AND #iAfterStockItemGroup <> 'chemicals'
RETURN 0
RETURN 1 -- will be executed only if the condition is false...
END
Then, alter your table to add the check constraint:
ALTER TABLE YourTableName
ADD CONSTRAINT ck_ConstraintName
CHECK (dbo.fn_FunctionName(fQuantity, iStockCodeID) = 1)
GO

Resources