Why I cannot get a result value from T-SQL function - sql

I'm trying to learn function in SQL Server, and I don't know why I cannot get a proper result from a T-SQL function.
The query what creates function is:
CREATE FUNCTION yuri_func1
(#valDate VARCHAR(10))
RETURNS VARCHAR
AS
BEGIN
DECLARE #valWeekday VARCHAR(10);
SET #valWeekday = DATENAME(WEEKDAY, #valDate);
RETURN #valWeekday;
END
And the other query is
select dbo.yuri_func1('2017-12-29') as [요일]
but the only result I got is just
Blank. (="")
But when I executed function like this,
select DATENAME(WEEKDAY, '2017-12-29')
the result was
MONDAY
I still don't get that why they return different results.
Does anybody know why?

This is because you should be accepting DateTime as a parameter in your function and not varchar
create Function yuri_func1 (#valDate DateTime) --Wrong parameter type
RETURN VARCHAR(10) -- No proper sizing of return type
AS
BEGIN
declare #valWeekday varCHAR(10);
Set #valWeekday = DATENAME(WEEKDAY,#valDate);
return #valWeekday;
END
GO

Related

Implicit conversion from data type datetime to int is not allowed. Use the coonvert function to run this query

I'm trying to return datetime variable from a stored procedure
RETURN #StatusCode >returns string
IF(#LastConnected IS NOT NULL)
RETURN #LastConnected >returns datetime (Error!!) when
I removed this line and it executes perfectly
Use SELECT instead of RETURN
CREATE PROCEDURE dbo.GetLastConnectedDate
--- INPUT PARAMETERS IF ANY
AS
BEGIN
SET NOCOUNT ON;
----- YOUR OTHER RELATED QUERIES
IF(#LastConnected IS NOT NULL)
SELECT #LastConnected ----- Use SELECT instead of RETURN here.
RETURN #StatusCode
END
GO

Creating a TSQL Shortcut for Converting to String

I'd like to write a user-defined function on SQL Server 2012 that converts any value to String/Text.
When i inspect SQL Server, the type of Convert function parameter is "expression", but I don't seem to be able to use this type for my own user-defined function. Is there any other alternative?
CREATE FUNCTION [dbo].[Text]
(
#value expression
)
RETURNS nvarchar(max)
AS
BEGIN
RETURN Convert(nvarchar(max), #value);
END
I receive the following error message:
Column, parameter, or variable #1: Cannot find data type expression.
Found the answer in case anyone is interested:
CREATE FUNCTION [dbo].[Text]
(
#value SQL_VARIANT
)
RETURNS nvarchar(max)
AS
BEGIN
RETURN Convert(nvarchar(max), ISNULL(#value,''));
END
Seems to do what I need it to.
Why you want to with the built in function, I don't know. However, the data type you want is sql_variant
CREATE FUNCTION [dbo].[Text]
(
#value sql_variant
)

How to pass more than one values as parameter to sql statement?

I have one big SQL query and I want to pull out some data using that query
declare #Period VARCHAR(10) = 'MTD'
declare #Date DATETIME = '2011-08-31'
and I have a big select statement where I'm passing above parameters and it executes the output.
Now I have 10 different dates which I need to pass here each time to see the result.
How can I pass those date to above parameter declare #Date DATETIME how can I hard code it ?
So my desired output will be for those selected dates, give me hint for at least 3 dates ?
Use a table-valued parameter. First, create a type:
CREATE TYPE dbo.Dates AS TABLE(d DATE);
Now your stored procedure can take this type as a parameter:
CREATE PROCEDURE dbo.whatever
#d dbo.Dates READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT t.columns
FROM dbo.tableName AS t
INNER JOIN #d AS d
ON t.[date] = d.d;
END
GO
Then from your application you can pass this parameter in as a DataTable, for example.

SQL Returning a datetime from a procedure results in Implicit conversion error

I'm fairly new to SQL and was trying to write a procedure that would check a passed in value and set a local datetime variable and then return that variable.
USE [MyDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Common].[Update_Date]
#Status_ID int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date_Value DATETIME
IF #Status_ID = 2
SET #Date_Value = GETDATE()
ELSE
SET #Date_Value = NULL
RETURN #Date_Value
END
GO
When I try to execute this script I get the following error:
Msg 257, Level 16, State 3, Procedure Update_Date, Line 19
Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.
Is it trying to do something with my #Status_ID parameter?
Stored procedures return values by using OUTPUT parameters:
CREATE PROCEDURE [Common].[Update_Date]
#Status_ID int,
#Date_Value DATETIME OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF #Status_ID = 2
SET #Date_Value = GETDATE()
ELSE
SET #Date_Value = NULL
END
GO
When invoked from ADO.Net, you use ParameterDirection.Output. From T-SQL you invoke with an OUTPUT clause:
declare #date DATETIME;
exec [Common].[Update_Date] 2, #date OUTPUT;
SELECT #date;
In general is better not to mix procedure output with the return and with the result set (so that would be a vote against most other recommendation you got to use SELECT). Using OUTPUT makes procedures reusable from other T-SQL code, using result set (SELECT) makes it much harder to use as T-SQL has problems capturing the result set of an invoked procedure (you'd have to use INSERT ... SELECT and deal with all the problems that has).
RETURN values in Stored Procedures can only be integers. Therefore youre getting an error converting #Date_Value to an int
It looks like you need a Function, not a Stored Procedure
CREATE FUNCTION (Transact-SQL)
Alternatively, you can change RETURN to SELECT, but I would recommend using a FUNCTION for this type of request.
The return value from a stored procedure must be an integer. The RETURN #Date_Value line is throwing the error.
I believe the return value of a stored procedure is an integer, and your return statement is converting the datetime to int. Can you do a select instead to return the value?
SELECT #Date_Value
Here is a link on return values, output values, and result sets that you might find useful:
http://sqlserverpedia.com/wiki/Stored_Procedures_-_Output_Parameters_%26_Return_Values
You don't have to use "return" to return a value, you use "select" to return the value. Just change the RETURN keyword at the end of your SP and use SELECT and i will work.
The Return keyword must be used to return an integer. Try changing it to Select #Date_Value
You had a few problems. Try this:
CREATE PROCEDURE [Common].[Update_Date](
#Status_ID INT
) AS
SET NOCOUNT ON
BEGIN
--will #Date_Value have an initial value of NULL????
DECLARE #Date_Value DATETIME
SET #Date_Value = NULL
IF #Status_ID = 2 BEGIN
SET #Date_Value = GETDATE()
END
SELECT #Date_Value
END

Unable to retrieve value returned from mysql function

Since a week am working with MYSQL , got to execute the Stored Procedure as well as Views but Facing some problem retrieving the values returned from a function.
Here's the Function:
CREATE DEFINER=`root`#`localhost` FUNCTION `GetProductIdsStringByEnquiryId`
(
InEnquiryId int
) RETURNS varchar(4000) CHARSET utf8
BEGIN
DECLARE InProductIds varchar(4000);
DECLARE ProductId varchar(50);
DECLARE x,y,z INT;
DECLARE sp1_cursor CURSOR FOR SELECT ProductId FROM enquiryproductid where
EnquiryId=InEnquiryId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET z = 1;
SET InProductIds='';
OPEN sp1_cursor;
REPEAT
FETCH sp1_cursor INTO ProductId;
SETInProductIds=concat(InProductIds,ProductId,',');
UNTIL (z=1)
END REPEAT;
CLOSE sp1_cursor;
RETURN InProductIds ;
END
I was initially working with SQL SERVER 2005, and the function which I have written in their I tried converting it as above in MYSQL,
Here's the SQL Function Code:
CREATE function [dbo].[GetBranchIdsStringByEmployeeId]
(
#EmployeeId as integer
)
returns nvarchar(4000)
as
begin
declare #BranchIds as nvarchar(4000)
set #BranchIds=''
if exists(select 1 from dbo.BranchEmployees where EmployeeId=#EmployeeId)
begin
select #BranchIds=#BranchIds+cast(BranchId as nvarchar(50))
+',' from dbo.BranchEmployees where EmployeeId=#EmployeeId
order by BranchId
end
return #BranchIds
end
Can anybody Please Let me know if the Function What I have written in MYSQL is in ProperManner or not? Please do help me out.
Thank You.
Not read fully through it, but few comments
Variable assignment in mysql uses := (in set #variable it is ok to use =, in select #variable:=#variable+1)
Are you trying to
SELECT group_concat(BranchId)
FROM dbo.BranchEmployees
WHERE EmployeeId = #EmployeeId
?