I have a DateSurragate Key column and i need a end of week column for that DateSurragate Key ,,,
I created a user defined function
CREATE FUNCTION dbo.fn (#dt date)
RETURNS date
AS
BEGIN
DECLARE #result date
select #result = dateadd(week, datediff(week, 0, #dt), 4)
RETURN #result;
END;
GO
This function works with date but when values like -1 and -2 are passed it gives NULL
PLEASE let me know how i can change this function so that it can handle integer values I am new to tsql
If my understanding is not wrong(to determine whether input value is valid date or not?)
USE ISDATE(expression) function:
EX:
DECLARE #datestring varchar(8)
SET #datestring = '12/21/98'
SELECT ISDATE(#datestring)
Similarly check for your input parameter within Function in the beginning.
Raise error or change the flow in func if ISDATE() return 0 in your case.
Related
I'm getting this error from the function:
CREATE FUNCTION getLavel(#id int ,#lavel char)
RETURNS date
BEGIN
DECLARE #date date
select #date = (select authorization_date from Authorized WHERE diver_number = #id and #lavel =level_name)
return #date
END
GO
What can be the reason?
Ty very much.
The function needs to be either the only function in the query window OR the only statement in the batch. If there are more statements in the query window, you can make it the only one "in the batch" by surrounding it with GO's.
e.g.
GO
CREATE FUNCTION getLavel(#id int ,#lavel char)
RETURNS date
BEGIN
DECLARE #date date
select #date = (select authorization_date from Authorized WHERE diver_number = #id and #lavel =level_name)
return #date
END
GO
Turn this into an inline table valued function. This will perform better than the scalar function. Also, you should NOT use the default sizes for character datatypes. Do you know what the default length for a char is? Did you know that it can vary based on usage?
CREATE FUNCTION getLavel
(
#id int
, #lavel char --You need to define the length instead of the default length
)
RETURNS table
return
select authorization_date
from Authorized
WHERE diver_number = #id
and #lavel = level_name
GO
You need to add RETURN before the END statement
That should fix your issue, that's what fixed mine. :D
Make sure that this statement is the only the only sql in your query window before you execute it.
Or you can highlight the function declaration and execute
What solved it for me, was that I was trying to create the function inside of a transaction context - that doesn't make sense from a SQL Server point of view. Transactions are for data, not functions.
Take the CREATE FUNCTION statement out of the transaction, then wrap it in GO's
CREATE FUNCTION CalculateAge(#DOB DATE)
RETURNS INT
AS
BEGIN
DECLARE #Age INT
SET #DOB='08/12/1990'
SET #Age =DATEDIFF(YEAR,#DOB,GETDATE()) -
CASE
WHEN (MONTH (#DOB)> MONTH (GETDATE ())) OR
(MONTH (#DOB)= MONTH (GETDATE ()) AND DAY (#DOB) >DAY (GETDATE ()))
THEN 1
ELSE 0
END
SELECT #Age
END
The Error is given to you in only query Page But if you execute the query then it will successfully execute.
CREATE FUNCTION getLavel(#id int ,#lavel char)
RETURNS date
BEGIN
DECLARE #date date
select #date = (select authorization_date from Authorized WHERE diver_number = #id and #lavel = level_name)
return #date
END
GO
Function 1:
I need to create an sql server function named FirstDayInQtr to return the first day in the respective quarter of year when a date is input. This function should be defined with the following header.
CREATE FUNCTION FirstDayInQtr(#InputDate datetime) RETURNS datetime AS…
Should return the date of first day in the respective quarter. like 1/1/2016
Function 2:
A function to check if an input string consists of UPPERCASE characters.
This function should be defined with the following header.
CREATE FUNCTION CheckStringOfUpperAlphaOK(#String varchar(MAX)) RETURNS varchar(6) AS…
Should return "okay" if true and "not okay" if false
simply create function in this way
Function 1 for getting first day in quarter
CREATE FUNCTION FirstDayInQtr(#InputDate datetime)
RETURNS datetime
AS
BEGIN
DECLARE #day datetime
SELECT #day = DATEADD(qq, DATEDIFF(qq ,0, #InputDate),0)
Return #day
END
Function2 For checking capital character as
CREATE FUNCTION CheckStringOfUpperAlphaOK(#String varchar(MAX))
Returns VarChar(6)
AS
Begin
Declare #KeepValues as varchar(50)
Set #KeepValues = '%[^ ][A-Z]%'
While PatIndex(#KeepValues collate Latin1_General_Bin, #Temp) > 0
Set #Temp = Stuff(#Temp, PatIndex(#KeepValues collate Latin1_General_Bin, #Temp) + 1, 0, ' ')
Return #Temp
End
This will get you the First Day of the Current Quater. I think thats what you are after
CREATE FUNCTION FirstDayInQtr(#InputDate DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE #firstDayOfCurrentQuater DATETIME
SELECT #firstDayOfCurrentQuater = DATEADD(qq, DATEDIFF(qq ,0, #InputDate),0)
RETURN #firstDayOfCurrentQuater;
END
I have the following function:
CREATE FUNCTION ISRELKDVG(#WUNSCH_LIEFERTERMIN VARCHAR) RETURNS int AS
BEGIN
DECLARE #sTerminNone VARCHAR(8)
DECLARE #sTerminFrom VARCHAR(8)
SET #sTerminNone = '00000000'
SET #sTerminFrom = CONVERT(VARCHAR(8), GETDATE() - 100, 112) -- 100 days in the past
IF (#WUNSCH_LIEFERTERMIN <> #sTerminNone AND #WUNSCH_LIEFERTERMIN >= #sTerminFrom)
RETURN 1
RETURN 0
END
The variable given as parameter to the function is a date and has a form "YYYYMMDD". The problem is that the function never returns 1.
I have found the link which says that comparing varchar's with unspecified length may lead to errors. Does it also refer to varchar's passed to the functions?
Do not rely on implicit conversions, using unknown dateformats. Convert to dates or datetimes, specifying a dateformat, and compare those values.
Specify the size of function parameter, e.g. varchar(8). Otherwise it is 1 character long by default:
declare #c as varchar
set #c = '20130101'
select #c -- returns 2
Try this out:
CREATE FUNCTION ISRELKDVG(#WUNSCH_LIEFERTERMIN VARCHAR(8)) RETURNS int AS
BEGIN
DECLARE #sTerminNone VARCHAR(8)
DECLARE #sTerminFrom DATE
SET #sTerminNone = '00000000'
IF (#WUNSCH_LIEFERTERMIN = #sTerminNone)
RETURN 0
SET #sTerminFrom = DATEADD(day,-100,GETDATE()) -- 100 days in the past
IF (CAST(#WUNSCH_LIEFERTERMIN AS DATE) >= #sTerminFrom)
RETURN 1
RETURN 0
END
select dbo.ISRELKDVG('00000000') --0
select dbo.ISRELKDVG('20030901') --0
select dbo.ISRELKDVG('20130901') --1
select dbo.ISRELKDVG('20130730') --1
Yes that is the main problem.
MSDN - Remarks
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
But (even in case of Cast/Convert), you should always define the length to avoid such troubles.
Change
#WUNSCH_LIEFERTERMIN VARCHAR --<--Length is 1 by default
To
#WUNSCH_LIEFERTERMIN VARCHAR(8) --Or length as appropriate
Secondly, you should be comparing Dates not Strings.
DECLARE #sTerminNone DATE = CONVERT(DATETIME, 0) --<--DATE (Assign correct date)
DECLARE #sTerminFrom DATE = GETDATE() - 100
Finally,
IF (CONVERT(DATE, #WUNSCH_LIEFERTERMIN, 112) <> #sTerminNone AND --Not sure if you need this
CONVERT(DATE, #WUNSCH_LIEFERTERMIN, 112) >= #sTerminFrom)
RETURN 1
ELSE
RETURN 0
Ideally, you should pass/define a DateType parameter to the function.
I have a function that I need to create that reads in the value of a column in a table and output a text value into a new column in the same table. The column in question (confidence_score) will have either a numeric value, a letter, or null value.
If confidence_score(nvarchar(2)) is a number and is less than or equal to 14, I need the computed column to have 'High' in it, otherwise 'Low'. If confidence_score is not a number and has a value of 'H', I need the computed column to have 'High' in it, otherwise 'Low'.
Here is the code I am using:
CREATE FUNCTION dbo.avm_confidence_level(#score nvarchar)
RETURNS nvarchar(5) as
BEGIN
DECLARE #conversion as nvarchar(5)
IF isnumeric(#score) = 1 BEGIN
IF cast(#score as int) <= 14 BEGIN
Set #conversion = 'High'
END
ELSE BEGIN
Set #conversion = 'Low'
END
END
ELSE BEGIN
IF #score = 'H' BEGIN
Set #conversion = 'High'
END
ELSE BEGIN
Set #conversion = 'Low'
END
END
RETURN #conversion
END
I am getting results using this code that are half right. The first check (isnumeric) seems to be working fine. I am getting High and Low values where I'm expecting them when the value is not a number. The issue seems to be within the isnumeric being true section. I am getting a value of 'High' regardless of what numeric value is actually in the confidence_score column. I'm not sure what I'm doing wrong here.
I appreciate any help anyone can offer.
Thank you.
It's because you defined the function parameter as nvarchar instead of nvarchar(2). It's truncating anything over one character, so all your ints above 9 are becoming 1. Try changing the definition to:
CREATE FUNCTION dbo.avm_confidence_level(#score nvarchar(2))
using this code :
ALTER PROCEDURE [dbo].[get](#i int)
AS
BEGIN
declare #ADate datetime
select #ADate = ADate
from table
where i=#i
and DateDiff(day ,getDate(), aDate ) > 0
and aDate is not null
order by aDate asc
return select #ADAte
END
this returns 0 (or system 0 date time, which is not the desired result from the data base).
execute code
Declare #res datetime
exec #res = get 3
print #res
why?
Stored Procedures in SQL Server can only RETURN integers. If you need to return anything other than a single integer, then you should use one of these methods (some explained by the previous answers):
Use a SELECT in your procedure
Use an OUTPUT Parameter
Use a User Defined Function instead
There isn't any need to declare a variable and assign a value to it. Just return the select statement.
ALTER PROCEDURE [dbo].[get](#i int)
AS
BEGIN
select ADate
from table
where i=#i
and DateDiff(day ,getDate(), aDate ) > 0
and aDate is not null
order by aDate asc
END
Although you should be aware that depending on your data this may return more than one value.
EDIT
If you want to you could do it this way:
ALTER PROCEDURE [dbo].[get](#i int, #date datetime output)
AS
BEGIN
select #date = ADate
from table
where i=#i
and DateDiff(day ,getDate(), aDate ) > 0
and aDate is not null
order by aDate asc
END
And then you can use it like so:
Declare #res datetime
exec get 3, #res
print #res
You should select the value:
select #OADate
Your value will be the first value in the first row on the first resultset.
Have a look at CREATE PROCEDURE
you need to use the OUTPUT clause
**OUTPUT**
Indicates that the parameter is a return parameter. The value of this option can be returned to EXEC[UTE]. Use OUTPUT parameters to return information to the calling procedure.
Also, returning a single value seems like it is calling for a USER DEFINED SCALAR FUNCTION, rather than a STORED PROCEDURE