I have created a function named 'fname'.
/*
create function fname(#ss int)
returns int
with schemabinding
as
begin
return #ss
end
*/
object_id('fname')
Now I want to get its id using object_id function by specifying its name. SQL Server gives an error
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near 'fname'.
Can anyone point what I am doing wrong? Thanks in advance.
You need to use the function under the SELECT statement
select object_id('fname')
I tried it and succeeded
create function fname(#ss int)
returns int
with schemabinding
as
begin
return #ss
end
go
select object_id('fname')
Related
I'm still trying to learn an SQL, i made a mistakes but i already search on the internet about the if statements...
I tried to create a simple function to check if the parameter is match the condition..
I have 2 parameters, that will be inputted manually by the users, but i got an error saying
Msg 156, Level 15, State 1, Procedure ufn_calculatebonus, Line 4 [Batch Start Line 1] Incorrect syntax near the keyword 'IF'. Msg 178, Level 15, State 1, Procedure ufn_calculatebonus, Line 10 [Batch Start Line 1] A RETURN statement with a return value cannot be used in this context.
This is the code i've tried to create, i thought i make the IF condition right? After the IF , should have a BEGIN and statements, closing it with END. ??
CREATE FUNCTION Sales.ufn_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
RETURNS TABLE
AS
IF #CompanyRevenue > 10
BEGIN
SELECT 'INPUT CANNOT BE BIGGER THAN 1000'
END
ELSE
BEGIN
RETURN
(
SELECT * FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter
);
END
GO
There are 2 distinct types of T-SQL table-valued functions, inline TVF and multi-statement TVF. The body of an inline TVF consists of only of a RETURNS statement with a query specification (not to be confused with a RETURN statement).
Your attempt at a multi-statement table-valued function is invalid for the reasons below.
The body of a multi-statement TVF must be surrounded with BEGIN...END.
A table variable with the returned schema must be declared in the function header.
One cannot return query results with a RETURN statement. Instead, insert results into the table variable declared in the function header end specify RETURN at the end of the function to return the results.
Below is an example of the remediated code. Importantly, note the use of an explicit column list throughout. Don't SELECT * in production code.
CREATE OR ALTER FUNCTION dbo.ufn_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
RETURNS #BalanceInfo TABLE (CustomerID int, Balance int, ErrorMessage varchar(100))
AS
BEGIN
IF #CompanyRevenue > 10
BEGIN
INSERT INTO #BalanceInfo (ErrorMessage) VALUES('INPUT CANNOT BE BIGGER THAN 1000');
END
ELSE
BEGIN
INSERT INTO #BalanceInfo (CustomerID, Balance) --note ErrorMessage is omitted and will be NULL
SELECT CustomerID, Balance FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter;
END;
RETURN;
END
GO
A stored procedure is a better fit than a than user-defined function if you need to raise custom errors for parameter validation. Here's a stored procedure example:
CREATE OR ALTER PROCEDURE dbo.usp_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
AS
IF #CompanyRevenue > 10
BEGIN
THROW 50000, 'INPUT CANNOT BE BIGGER THAN 1000', 16;
END;
SELECT CustomerID, Balance FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter;
GO
I'm trying to create the function in SQL Server. In this function I have generated the random number, but function not generated.
Create function [GetRandomNumber]
(
)
RETURNS bigint
as
Begin
Declare #randomNo int
set #randomNo = (select round(rand(checksum(newid()))*(10001)+50000,0) as [GetRandomNumber])
return #randomNo
End
this is generated in following error:
Invalid use of a side-effecting operator 'newid' within a function.
Msg 443, Level 16, State 1, Procedure GetRandomNumber, Line 8
Invalid use of a side-effecting operator 'rand' within a function.
You can. However, it will require a little bit of extra legwork.
First, you need to create a view, like the one below:
create view dbo.sys_NDF
as
select rand() as [ValueRand], newid() as [ValueGUID],
rand(checksum(newid())) as [SeededRand];
go
The trick is that you cannot call these system functions directly from your UDF, however you can query a view that returns their values. You can later expand it with other functions / columns if need be.
As such, your function starts to look like the following:
Create function [GetRandomNumber]()
RETURNS bigint as begin
return (select round(v.SeededRand * 10001 + 50000, 0) from dbo.sys_NDF v);
end;
go
Create SP instead of function. Because some system function are not allowed in user defined function.
CREATE PROCEDURE [GetRandomNumber]
as
Begin
Declare #randomNo int
set #randomNo = (select round(rand(checksum(newid()))*(10001)+50000,0) as [GetRandomNumber])
return #randomNo
End
GO
DECLARE #returnvalue INT
EXEC #returnvalue = GetRandomNumber
SELECT #returnvalue
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.
Hello i am trying to create a function in ms sql server that accepts an integer parameter and returns a varchar. I am however having some trouble implementing this and would really love some help with this:
CREATE FUNCTION GetCategory (#CategoryID int)
RETURNS int
AS
BEGIN
DECLARE #Category varchar(64)
#Category = (SELECT Category
FROM Categories
WHERE CategoryID = #CategoryID)
RETURN #Category
END
The code above is what i tried doing already. I get the following error upon execution:=:
Msg 102, Level 15, State 1, Procedure GetCategory, Line 7
Incorrect syntax near '#Category'.
Msg 137, Level 15, State 2, Procedure GetCategory, Line 11
Must declare the scalar variable "#Category".
If Column CategoryID is a Primary key in your table and you are 100% sure there will be only ONE Category with a particualr CategoryID then your code is safe, but if it isnt a primary key and you can possibly have multiple Categories with same CategoryID then I would suggest using SELECT TOP 1 in your select statement.
CREATE FUNCTION GetCategory (#CategoryID int)
RETURNS varchar(64) --<-- This needs to be the datatype you want to return
AS
BEGIN
DECLARE #Category varchar(64);
SELECT #Category = Category
FROM Categories
WHERE CategoryID = #CategoryID
RETURN #Category;
END
Calling Function
SELECT dbo.GetCategory (1);
You say RETURNS int when actually you return a varchar 64.
Also when asking a question and posting sample code of what doesn't work it helps if you say "what" doesn't work. (what error message you get etc).
Getting very annoyed with this simple query...
I need to add an offset to a varchar, if it's a number and do nothing is it is not.
For this reason I've created the following function in SQL-server.
I then extract the answer with:
select dbo.OffsetKPL("100",200)
However this does not work, I get the error
Msg 207, Level 16, State 1, Line 1
Invalid column name '100'.
The code for the function is as follows...
ALTER FUNCTION [dbo].[OffsetKPL](
#kpl varchar(20)
,#offset int = 0
)
RETURNS varchar(20)
AS
BEGIN
DECLARE #uitkomst varchar(20);
set #uitkomst = #kpl;
if not(#offset = 0) begin
if (IsNumeric(#uitkomst) = 1) begin
set #uitkomst = cast((cast(#kpl as int) + #offset) as varchar);
end;
end;
RETURN #uitkomst;
END
What's wrong? nowhere does it state that IsNumeric does not accept a variable.
Use single quotes for strings!
select dbo.OffsetKPL('100',200)
If you have QUOTED_IDENTIFIER on (the default) things in double quotes are expected to be object names.
isnumeric may not be what you need though as all kinds of unexpected things return 1 for this.
SELECT ISNUMERIC('$'), ISNUMERIC('.'),
ISNUMERIC('12d5'), ISNUMERIC(','), ISNUMERIC('1e1')
See IsNumeric() Broken? Only up to a point for some discussion on this point.