Calling a custom SQL function - sql

This feels like a basic question, but I have tried everything! I'm writing a custom function SQL function to convert integers into dates:
CREATE FUNCTION convert_to_date (#fin INT)
RETURNS DATE
AS
BEGIN
DECLARE #fout DATE
SET #fout = CASE WHEN #fin IN ('','99999999','0','1') THEN NULL
ELSE CONVERT(DATE,CAST(#fin AS CHAR(8)))
END
RETURN #fout
END
SELECT dbo.convert_to_date(DtSurgDischarge) AS DischargeDate
FROM [TR_MASTER.registry].[dbo].[mgh_tumor]
I get the following error message:
Msg 156, Level 15, State 1, Procedure convert_to_date, Line 16
Incorrect syntax near the keyword 'SELECT'.
What am I doing wrong? Feels like it must be obvious. Thanks everyone!

At the very least you need a GO after the END statement of the function, if you're attempting to execute both the function create and the SELECT in one script - assuming you're using SSMS to run the script, that is.
CREATE FUNCTION convert_to_date (#fin INT)
RETURNS DATE
AS
BEGIN
DECLARE #fout DATE
SET #fout = CASE WHEN #fin IN ('','99999999','0','1') THEN NULL
ELSE CONVERT(DATE,CAST(#fin AS CHAR(8)))
END
RETURN #fout
END
GO
SELECT dbo.convert_to_date(DtSurgDischarge) AS DischargeDate
FROM [TR_MASTER.registry].[dbo].[mgh_tumor]

Related

T-SQL Scalar-valued function Return Null value

I'm trying to create a Scalar-valued user defined function to substitute my original codes. Basically, I intend to calculate the percentage of 2022 "nnooftickets" data out of the 2020 data for each period, there are 13 period in a year. Unfortunately, my user defined function codes do not work and I'm struggling spotting the issue.
The following are the original codes that works fine:
SELECT
setperiod,
SUM(nnooftickets) AS sumnnoofticketsp,
CASE
WHEN setperiod like '2023%' THEN SUM(nnooftickets) *1.00 / LAG(SUM(nnooftickets),13*(2023-2020)) OVER(ORDER BY setperiod) ELSE null
END AS nnoofticketspyoy
FROM rdg.Sales
GROUP BY setperiod
Then I created a scalar function try to replace the case statement, the codes for the scalar function is as follows:
CREATE FUNCTION [rdg].[getyoy]
(
#var BIGINT, #currentyear SMALLINT, #compareyear SMALLINT, #orderbyperiod VARCHAR, #multiplygap SMALLINT
)
RETURNS DECIMAL(18,4)
AS
BEGIN
DECLARE #YOY AS DECIMAL(18,4)
SELECT #YOY = CASE WHEN #orderbyperiod like '2023%' THEN #Var*1.00 / LAG(#Var, #multiplygap*(#currentyear - #compareyear)) OVER (ORDER BY #orderbyperiod) ELSE null END
RETURN #YOY
END
GO
Finally, I call the function using the codes below:
SELECT
setperiod,
SUM(nnooftickets) AS sumnnoofticketsp,
rdg.getyoy(SUM(nnooftickets), 2023, 2020, setperiod, 13) AS ngrosspyoy
FROM rdg.Sales
GROUP BY setperiod
However, after using the scalar function, there's no output figure (i.e. receive all NULL values) for column ngrosspyoy.
Could anyone help please?

sql stored function gives an error

I am trying to create a stored function to take one parameter called budget. The function should return the string 'LOW' for a budget less than or equal to 500000, 'MID' for a budget less than or equal to 850000, 'HIGH' for a budget less than or equal to 1200000, and 'ULTRA' for a budget above 1200000. But I am getting an error that doesn't make much sense to me.
Here is my function:
set term # ;
create procedure f_rating(budget int)
as
begin
if (budget <= 500000) then
return ('LOW');
else if (budget <= 850000) then
return ('MID');
else if (budget <= 1200000) then
return ('HIGH');
else
return ('ULTRA');
end #
I am still new to sql, so this syntax is based on examples online and such. Here is my error:
SQL Message : -804
An error was found in the application program input parameters for the SQL statement.
Engine Code : 335544569
Engine Message :
Dynamic SQL Error
SQL error code = -804
Function unknown
RETURN
Can anyone help me figure out what this means?
The syntax for stored function is
CREATE FUNCTION funcname [ ( [ <in_params> ] ) ]
RETURNS <domain_or_non_array_type> [COLLATE collation]
[DETERMINISTIC]
<module-body>
So you have made two mistakes, you use procedure instead of function and you miss the RETURNS <type> part. Try
create function f_rating(budget int) RETURNS VARCHAR(5)
as
begin
if (budget <= 500000) then
return 'LOW';
else if (budget <= 850000) then
return 'MID';
else if (budget <= 1200000) then
return 'HIGH';
else
return 'ULTRA';
end #
procedure does not return any value, functions do.
Try:
create function f_rating(budget int)
as
instead of
create procedure f_rating(budget int)
as

Rerun Error Message While Creating a Function

i am fairly new to SQL programming, and I am currently learning to create FUNCTIONS.
The problem that I am having, is creating the following FUNCTION.
create function CreatePI
(
)
returns decimal(10,6)
with returns null on null input
as
begin
declare #P as decimal(10,6)
set #P = 4*(1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)+(1/13)-(1/15)
return #P
end
go
The above function is supposed to replicate the number PI. But the problem that I am having is:
Msg 156, Level 15, State 1, Procedure CreatePI, Line 11
Incorrect syntax near the keyword 'return'.
If anyone could help me out with why I am getting this problem, it would be greatly appriciatead.
You are missing a closing paren on the set line:
set #P = 4*(1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)+(1/13)-(1/15))
----------------------------------------------------------^

getting error for if/else in a stored procedure

I am relatively very new to SQL queries but I have this stored procedure where I am trying to get value of a declared variable as mentioned below but getting error,
First line is 20 here,
declare #m_ID_v int
set #m_ID_v = ( select ID_C from M_T where MName_C = #MName_parameter)
declare #g bit
if (select G_L_Column from G_L_table Where M_ID_Column = #M_ID_variable)
set #g_v = 1
else
set #g_variable = 0
Exception I get:
Msg 4145, Level 15, State 1, Procedure GetID, Line 20
An expression of non-boolean type specified in a context where a
condition is expected, near 'set'. Msg 156, Level 15, State 1,
Procedure GetID, Line 21 Incorrect syntax near the keyword 'else'.
Now if I remove declare #g... and try to parse it, no error occurs
EDIT
I want my code to check for returned value by my select statement so "if exists" is not really what am looking for, sorry.
try use if exists:
declare #g_v bit
if exists(select G_L_Column from G_L_table Where M_ID_Column = #M_ID_variable)
set #g_v = 1
else
set #g_v = 0
declare #m_ID_v int
set #m_ID_v = ( select ID_C from M_T where MName_C = #MName_parameter)
declare #g bit
if ((select G_L_Column from G_L_table Where M_ID_Column = #M_ID_variable) = value )
set #g_v = 1
else
set #g_variable = 0
You can't say
if (select ...
You have to compare something with something else in a if statement, or use a boolean function such as exists

Error using the export data option in SQL Server 2008 with function

This is probably an easy question to answer, but I can't figure it out.
I have this query which I want to export to Excel. I followed instructions detailed here, but the sql query is not right because of the use of a function I defined earlier.
This is the function I defined:
CREATE FUNCTION FullMonthsSeparation
(
#DateA DATETIME,
#DateB DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE #Result INT
DECLARE #DateX DATETIME
DECLARE #DateY DATETIME
IF(#DateA < #DateB)
BEGIN
SET #DateX = #DateA
SET #DateY = #DateB
END
ELSE
BEGIN
SET #DateX = #DateB
SET #DateY = #DateA
END
SET #Result = (
SELECT
CASE
WHEN DATEPART(DAY, #DateX) > DATEPART(DAY, #DateY)
THEN DATEDIFF(MONTH, #DateX, #DateY) - 1
ELSE DATEDIFF(MONTH, #DateX, #DateY)
END
)
RETURN #Result
END
GO
This is the SQL Query that I want to export to Excel:
SELECT DISTINCT soc.idSocio,
(SELECT Count(*)
FROM [BaseSR].[dbo].[Movimiento] m
WHERE m.idSocio = soc.idSocio
AND m.TipoMovimiento = 1) AS CantidadDeCompras,
nombre,
(SELECT TOP 1 fecha
FROM [BaseSR].[dbo].[Movimiento] m
WHERE m.idSocio = soc.idSocio
AND m.TipoMovimiento = 1/*Consumos*/
ORDER BY fecha DESC) AS UltimoMovimiento,
dbo.Fullmonthsseparation(soc.fechaAlta, Getdate()) AS MesesDesdeAltaEnPrograma
FROM [BaseSR].[dbo].[Socio] soc
WHERE soc.idTarjeta LIKE '2001%'
And this is the error message I get:
The statement could not be parsed. Additional information: Deferred
prepare could not be completed. Statement(s) could not be prepared.
Cannot find either column "dbo" or the user-defined function or
aggregate "dbo.FullMonthsSeparation", or the name is ambiguous.
However, when I execute the query it runs without any problem.
If I changed the sql query to [BaseSR].dbo.FullMonthsSeparation(... then the error is:
The statement could not be parsed. Additional information: Deferred
prepare could not be completed. Statement(s) could not be prepared.
Cannot find either column "BaseSR" or the user-defined function or
aggregate "BaseSR.dbo.FullMonthsSeparation", or the name is ambiguous.
Any ideas?
You've justified out the database names everywhere, which suggests the execution context is not [BaseSR], which would explain why the function might not be found.
Try doing the same for the function:
[BaseSR].dbo.FullMonthsSeparation(...
I would suggest to take easy way- create view and export data from there! :)