Using SYSTEM_USER as a parameter to a table valued function - sql

I've created a table valued function:
CREATE FUNCTION TestFunction
(
#username VARCHAR(80)
)
RETURNS TABLE
AS
RETURN
(
SELECT 0 AS TestValue
)
Then try to call it as so:
SELECT TestValue
FROM dbo.TestFunction(SYSTEM_USER)
but get the error:
Incorrect syntax near the keyword 'SYSTEM_USER'
I've even tried making this a table valued function which is not inline, but I get the same error.
Am I missing something? Why am I getting this error?

On my 2k8 server I can only reproduce that with SQL Server 2000 (80) Compatibility level set, check the level of your 2005 database.
Meantime you can;
declare #su varchar(30) = SYSTEM_USER
select * from dbo.TestFunction(#su)

Related

SQL Server table-valued function Parameters were not supplied for the function-

I keep getting the error : "Parameters were not supplied" for a very simple table-valued function. I cannot figure out what is the issue. I narrowed the function down to :
create FUNCTION udf_XX_OddFCST()
RETURNS #output TABLE (
articlecode nvarchar(50)
)
AS
BEGIN
insert into #output(articlecode) values ('abc');
RETURN
END
So I get the error when executing
select * from udf_XX_OddFCST
Any help would be greatly appreciated.
kind regards
you need to use parentheses in your function call :
SELECT * FROM udf_XX_OddFCST()
however as it has been mentioned in the comments, it would be more simpler and more efficient using iTVF:
CREATE FUNCTION udf_XX_OddFCST()
RETURNS TABLE
AS
RETURN (select 'abc' as articlecode)
SELECT * FROM udf_XX_OddFCST()

Linked Table Valued Function Parameters (SQL Server)

I need to create a SQL Server TVF that takes a single param and then used that param to build the other required parameters. Is this even possible?
The error states incorrect syntax near 'LEFT'. Simple representation below.
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC',
#PRM2 VARCHAR(1) = LEFT(#PRM1,1)
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT #PRM2
)
GO
Thank You!
BEFORE EDIT MADE IN THE QUESTION :
You need only one parameters :
SELECT #PRM2 = LEFT(#PRM1, 1);
However, you need scaler function not table valued function :
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC'
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE #PRM2 VARCHAR(255)
SET #PRM2 = LEFT(#PRM1, 1)
RETURNS (#PRM2)
END
Note : Your #PRM1 will accept only two characters which are AB. So, define appropriate length.

Getting error while running function using T-SQL

I have created small table value function using T-SQL which takes one input parameter phone number as and returns area code from it. Function compiles successfully but when I run it I am getting error:
Msg 4121, Level 16, State 1, Line 1776
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.getareacode1", or the name is ambiguous
Refer to my code:
create or alter function dbo.getareacode1 (#phoneno as nvarchar(20))
returns table
with schemabinding
as
return
(select top 1
#phoneno as PhoneNumber, value as AreaCode
from
string_split(#phoneno,'-')
);
select dbo.getareacode1( N'323-234-2111');
First off, the order of the rows returned from STRING_SPLIT is not guaranteed, so this function broken to begin with.
But the error is caused by trying to invoke a Table-Valued Function where a scalar is expected.
A TVF cannot be treated like a scalar function. So
create or alter function dbo.getareacode1 (#phoneno as nvarchar(20))
returns table
with schemabinding
as
return
(
select top 1 #phoneno as PhoneNumber, value as AreaCode
from string_split(#phoneno,'-')
);
go
select * from dbo.getareacode1( N'323-234-2111');
And if you want to call it from another query use CROSS APPLY, eg
with phoneNumbers as
(
select N'323-234-2111' phoneno
from sys.objects
)
select ac.*
from phoneNumbers p
cross apply dbo.getareacode1(p.phoneno) ac;
On the flip-side of what David said: for your function to work like you were expecting you will need a scalar user-defined function (udf). This function:
-- Create function
create or alter function dbo.getareacode1 (#phoneno as nvarchar(20))
returns nvarchar(20) with schemabinding as
begin
return
(
select top (1) AreaCode = ss.[value]
from string_split(#phoneno,'-') ss
);
end
GO
... will allow this query to work:
select dbo.getareacode1( N'323-234-2111');
All that said, I strongly advise against using scalar udfs. I'll include a a couple good links that explain why at the bottom of this post. Leaving your function as-is and using APPLY, as David demonstrated, is the way to go. Also, string_split is not required here. If phone numbers are always coming in this format: NNN-NNN-NNNN, you could just use SUBSTRING:
SUBSTRING(N'323-234-2111', 1, 3).
For countries with varible-length area codes in the format (area code(2 or more digits))-NNN-NNNN you could do this:
declare #phoneno nvarchar(30) = N'39-234-2111'; -- Using a variable for brevity
select substring(#phoneno,1, charindex('-',#phoneno)-1);
If you, for whatever reason, really need a function, then this is how I'd write it:
-- using the variable-length requirement as an example
create or alter function dbo.getareacode1_itvf(#phoneno as nvarchar(20))
returns table with schemabinding as
return (select areacode = substring(#phoneno,1, charindex('-',#phoneno)-1));
go
Great articles about Scalar UDFs and why iTVFs are better:
How to Make Scalar UDFs Run Faster -- Jeff Moden
Scalar functions, inlining, and performance -- Adam Machanic
TSQL Scalar functions are evil – Andy Irving -- Stackoerflow post

Error converting data type nvarchar to datetime with stored procedure

[Using SQL Server 2008 R2 Enterprise x64 SP1]
I am trying to use some form of GETDATE() to pass today's date to a stored procedure inside OPENQUERY(), but I keep getting the error
Msg 8114, Level 16, State 1, Procedure spCalcProjection, Line 0
Error converting data type nvarchar to datetime
Here is the code (spCalcProjection takes a datetime):
SELECT top 1 multi FROM OPENQUERY([production], 'exec proddb.dbo.spCalcProjection "GETDATE()"')
If I use 2014-05-22 or any literal in place of GETDATE() then I have no problem and get the correct, expected result. If I use some other functionality like CAST(GETDATE() AS DATE) or CONVERT(varchar, GETDATE(), 112) then I get the above error again.
Conrad, posting original syntax error for GETDATE() without double quotes could help more than you think. I also don't see why would you need to escape the function here. (Sorry, can't add to your thread with Lamak, not enough reputation for comments). Also, why do you need an open query to call your sp? When you say SQL Server 2008 R2, is it both on the calling side and on your [production] server? If the other end is not SQL Server it might not have GETDATE() function. If the other end is SQL Server you don't need OpenQuery.
[UPDATE]
I think I have your answer. You cannot use a function as a parameter for stored procedure. Has nothing to do with open query. What you can do, you can replace that stored procedure with table-valued function. I just tried it and it worked.
Definition:
CREATE FUNCTION TestFun
(
#TestDateParam datetime
)
RETURNS
#RetTable TABLE
(
Line nvarchar(20)
)
AS
BEGIN
INSERT INTO #RetTable
SELECT aString
FROM sometable
WHERE aDate = #TestDateParam
RETURN
END
Call:
SELECT *
FROM dbname.dbo.TestFun(GETDATE())
Got an answer from elsewhere that I will use:
SELECT top 1 multi FROM OPENQUERY([production], 'DECLARE #dt datetime SELECT #dt = GETDATE() exec proddb.dbo.spCalcProjection #dt')
This avoids having to create any additional objects in the db.

Calling Scalar-valued Functions in SQL

I have migrated a database from oracle, and now have a few Scalar-valued Functions.
However, when I call them, I get an error saying:
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.chk_mgr", or the name is ambiguous.
I'm calling it like this:
SELECT dbo.chk_mgr('asdf')
What am I doing wrong?
Are you sure it's not a Table-Valued Function?
The reason I ask:
CREATE FUNCTION dbo.chk_mgr(#mgr VARCHAR(50))
RETURNS #mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN
INSERT #mgr_table (mgr_name) VALUES ('pointy haired boss')
RETURN
END
GO
SELECT dbo.chk_mgr('asdf')
GO
Result:
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function
or aggregate "dbo.chk_mgr", or the name is ambiguous.
However...
SELECT * FROM dbo.chk_mgr('asdf')
mgr_name
------------------
pointy haired boss
Can do the following
PRINT dbo.[FunctionName] ( [Parameter/Argument] )
E.g.:
PRINT dbo.StringSplit('77,54')
That syntax works fine for me:
CREATE FUNCTION dbo.test_func
(#in varchar(20))
RETURNS INT
AS
BEGIN
RETURN 1
END
GO
SELECT dbo.test_func('blah')
Are you sure that the function exists as a function and under the dbo schema?
You are using an inline table value function. Therefore you must use Select * From function.
If you want to use select function() you must use a scalar function.
https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx
Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.