Error in running scalar-valued function when different calling method is used - sql-server-2012

I have this function
CREATE FUNCTION fullName
(
#customer_id int
)
RETURNS varchar(50)
AS
BEGIN
DECLARE #name varchar(50)
SELECT #name = (SELECT name_last + ', ' + name_first FROM DT_CUSTOMERS WHERE customer_id = #customer_id)
RETURN #name
END
When I call/run the function with this code, it works:
SELECT dbo.fullName(356)
But when I use this method, it gives me the error "Invalid object name 'fullName'" with or without the "dbo." before the function name :
SELECT * FROM fullName(356)

Related

What's the limit of a variable in T-SQL? Why does my variable prints out as NULL?

I'm creating a stored procedure with the following code:
CREATE OR ALTER PROCEDURE Insert_Into_Table
#Origin VARCHAR(255),
#Destination VARCHAR(255),
#Origin_Columns VARCHAR (4000),
#Destination_Columns VARCHAR (4000),
#Delete_Date_Column_Name VARCHAR(63), --Nullable
#Delete_Period_Months INT -- Nullable
AS
BEGIN TRY
DECLARE #insert_query VARCHAR(4000) = NULL;
DECLARE #delete_query VARCHAR(4000) = NULL;
DECLARE #check_query VARCHAR (4000) = NULL;
DECLARE #Date_To_Delete DATETIME = CAST(DATEADD(MONTH, -#Delete_Period_Months, GETDATE()) AS DATETIME);
-- Table names cannot be referenced directly in SPs, so we bypass
-- this issue by declaring a variable containing the query
IF #Delete_Date_Column_Name IS NOT NULL
OR #Delete_Period_Months IS NOT NULL
SET #delete_query = 'DELETE FROM ' + #Destination + ' WHERE ' +
#Delete_Date_Column_Name + ' >= ' + CONCAT(CHAR(39),CAST(#Date_To_Delete AS VARCHAR(255)),CHAR(39));
ELSE
PRINT N'Missing or no values provided for table deletion. Only executing copy';
CREATE TABLE #temptable (count INT)
SET #check_query = 'INSERT INTO #temptable SELECT TOP 1 1 AS count FROM ' + #Origin
EXECUTE(#check_query)
SET #insert_query = 'INSERT INTO' + QUOTENAME(#Destination) + QUOTENAME(#Destination_Columns, '()') +
'SELECT ' + #Origin_Columns + ' FROM ' + QUOTENAME(#Origin);
BEGIN TRY
IF EXISTS (SELECT TOP 1 * FROM #temptable)
BEGIN TRANSACTION
EXECUTE(#delete_query);
EXECUTE(#insert_query);
COMMIT
END TRY
BEGIN CATCH
ROLLBACK;
THROW 51000, 'The Origin table is empty', 1;
END CATCH
END TRY
BEGIN CATCH
THROW 51000, 'Error creating transaction', 1;
END CATCH
GO
When executing the stored proecedure with the parameters shown, it works correctly:
EXEC Insert_Into_Table
#Origin = 'Sink_Proc',
#Destination = 'Sink_Test',
#Origin_Columns = 'customer, order_number, created_date',
#Destination_Columns = 'customer, order_number, created_date',
#Delete_Date_Column_Name = NULL,
#Delete_Period_Months = NULL
However, when executing it with 25+ columns as Origin/Destination columns, when I print the #insert_query variable, it returns NULL and no operation is done. Why is this happening?

How to execute the sql function

How can I execute this function?
I tried as Select [dbo].[GetPaidInfo]("1"), but I get the error:
An insufficient number of arguments were supplied for the procedure or
function dbo.GetPaidInfo.
USE [PCJ_BM]
GO
/****** Object: UserDefinedFunction [dbo].[GetPaidInfo] Script Date: 3/24/2018 5:05:15 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetPaidInfo] (
#InvId INT
,#PmtType VARCHAR(10)
)
RETURNS NVARCHAR(200)
AS
BEGIN
-- Declare the return variable here
DECLARE #PaidInfo NVARCHAR(200)
DECLARE #payment2 VARCHAR(50) = ''
DECLARE #payment3 VARCHAR(50) = ''
DECLARE #card VARCHAR(50) = (
SELECT Card
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Currency2 VARCHAR(50) = (
SELECT Currency2
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Amt2 VARCHAR(50) = (
SELECT Amt2
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Currency3 VARCHAR(50) = (
SELECT Currency3
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Amt3 VARCHAR(50) = (
SELECT Amt3
FROM Payment
WHERE (InvId = #InvId)
)
IF (#PmtType = 'Cash')
BEGIN
IF (#Currency2 != NULL OR #Currency2 != '')
BEGIN
SET #payment2 = ' + ' + #Currency2 + ' ' + #Amt2
END
IF (#Currency3 != NULL OR #Currency3 != '')
BEGIN
SET #payment3 = ' + ' + #Currency3 + ' ' + #Amt3
END
SET #PaidInfo = (
SELECT 'Paid in Cash by ' + Currency1 + ' ' + CONVERT(VARCHAR, Amt1) + #payment2 + #payment3
FROM Payment
WHERE (InvId = #InvId)
)
END
ELSE
BEGIN
SET #PaidInfo = (
SELECT 'Paid in Card by ' + CONVERT(VARCHAR, Amt1) --, Currency2, Amt2, Currency3, Amt3
FROM Payment
WHERE (InvId = #InvId)
)
END
-- Return the result of the function
RETURN #PaidInfo
END
My table looks like:
Call your function like this (INT no quotes, VARCHAR(10) single quotes):
SELECT [dbo].[GetPaidInfo] (1,'Cash');
Be aware your function returns NVARCHAR(200).
It appears you are planning to concatenate some information there, so if you start to see some of your string truncated, you might want to increase the length.
As per function definition, it requires 2 params : #InvId & #PmtType.
You should pass both of them during function call like follows:-
SELECT dbo.GetPaidInfo(2, 'Card');

How to select the ALL passed parameter values inside the stored procedure in SQL like SQL Trace

How to select all parameters and values passed to the stored procedure as like in SQL Trace, inside the procedure using any ## function without any customization.
For Example I have a stored procedure like
CREATE PROC test_Procedure
#ln varchar(25) = '',
#fn varchar(25) = '',
#dob datetime = NULL,
#id INT = 0
AS
BEGIN
SELECT * FROM tb_users
WHERE ln= #ln
AND fn = #fn
AND dob = #dob
AND Id = #id
------------ SELECT ##
END
If I called the procedure like
EXEC [dbo].test_Procedure #ln = N'a',#fn = NULL,#dob = NULL,#id = 1
I need to select this exact string inside the procedure using any built in function or user defined function .
If you're trying to output debugging style info you could use something like this;
SELECT CONCAT('test_Procedure #ln = ', #ln, ', #fn = ', #fn, ', #dob = ', #dob, ', #id = ', #id)

Why is SQL output parameter always null

I have the following SP
CREATE PROCEDURE [dbo].[GetBaseSixtyTwoString]
#a_number_to_convert int,
#v_temp_val nvarchar(256) output
AS
DECLARE #v_modulo INTEGER;
DECLARE #v_temp_int decimal(38) = #a_number_to_convert;
DECLARE #v_temp_char VARCHAR(1);
DECLARE #c_base62_digits VARCHAR(62) = '0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ';
IF ( #a_number_to_convert = 0 )
BEGIN
SET #v_temp_val = '5';
END
WHILE ( #v_temp_int <> 0 )
BEGIN
SET #v_modulo = #v_temp_int % 62;
SET #v_temp_char = substring( #c_base62_digits, #v_modulo + 1, 1 );
SET #v_temp_val = #v_temp_char + #v_temp_val;
SET #v_temp_int = floor(#v_temp_int / 62);
END
I am calling it like this:
declare #shorturl nvarchar(256)
exec dbo.GetBaseSixtyTwoString 1, #shorturl output
But the variable #shorturl always returns null
However if I put print statements in the SP I can see that #v_temp_val is indeed getting the correct value.
What am I missing?
You need to initialise #v_temp_val inside the stored procedure to non-NULL value, to ''.
If #v_temp_val is NULL, then this line would still result in NULL:
SET #v_temp_val = #v_temp_char + #v_temp_val;
because "value" + NULL = NULL
check if any value you put into variable #v_temp_val is null. note that any non-null value + NULL will result to NULL:
SET #v_temp_val = ISNULL(#v_temp_char, '') + ISNULL(#v_temp_val, '');

How to extract an ID number from a URL string in SQL?

I am trying to extract an ID from a URL and running into some issues. The URL's will look something like this:
http://www.website.com/news/view.aspx?id=95
http://www.website.com/news/view.aspx?id=20&ReturnURL=%2fnews%2fview.aspx%3fid%3d20
I am trying to return back the number following "?id=" and nothing after the number. I will then convert it to an INT in reference to another table. Any suggestions as how to do this properly?
Use charindex to find the position of ?id and stuff to remove the characters that is before ?id. Then you use left to return the characters to the next &
declare #T table
(
URL varchar(100)
);
insert into #T values
('http://www.website.com/news/view.aspx?id=95'),
('http://www.website.com/news/view.aspx?id=20&ReturnURL=%2fnews%2fview.aspx%3fid%3d20');
select left(T2.URL, charindex('&', T2.URL) - 1) as ID
from #T as T
cross apply (select stuff(T.URL, 1, charindex('?id', T.URL) + 3, '')+'&') as T2(URL);
Here is an option that you can use when you want to find the value of any parameter value within a URL, it also supports parsing text values that contain a URL
DECLARE #Param varchar(50) = 'event'
DECLARE #Data varchar(8000) = 'User Logged into https://my.website.org/default.aspx?id=3066&event=49de&event=true from ip'
DECLARE #ParamIndex int = (select PatIndex('%'+#param+'=%', #Data)+LEN(#param)+1)
-- #ParamValueSubstring chops off everthing before the first instance of the parameter value
DECLARE #ParamValueSubstring varchar(8000) = SubString(#Data, #ParamIndex, 8000)
SELECT #ParamValueSubstring as ParamSubstring
DECLARE #SpaceIndex int = (SELECT CHARINDEX(' ', #ParamValueSubstring))-1
DECLARE #AmpIndex int = (SELECT CHARINDEX('&', #ParamValueSubstring))-1
DECLARE #valueLength int = -1
-- find first instance of ' ' or & after parameter value
IF #SpaceIndex = -1
SET #valueLength = #AmpIndex
ELSE IF #AmpIndex = -1
SET #valueLength = #SpaceIndex
ELSE IF #SpaceIndex < #AmpIndex
SET #valueLength = #SpaceIndex
ELSE
SET #valueLength = #AmpIndex
IF(#valueLength = -1) -- check to see if there was no space or '&' following the parameter value
BEGIN
SET #valueLength = 8000
END
select Left(#ParamValueSubstring, #valueLength) as ParamValue
-- approach similar to idea function found here http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server/
I'm not totally clear on what you're asking. Are you asking how to get the value of id from the url when you are in the asp.net application? Then in the code behind you can
In c#
string id = Request.QueryString["id"]; // returns null if id not found
Reference
From this SO question Try this for integers:
int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}
You could do it in an SQL function, like this:
declare #URL varchar(100)
--set #URL = 'http://www.website.com/news/view.aspx?id=95'
set #URL = 'http://www.website.com/news/view.aspx?id=20&ReturnURL=%2fnews%2fview.aspx%3fid%3d20'
Set #URL = CASE charindex('&',#URL)
WHEN 0 then #URL else substring(#url,1,charindex('&',#URL)-1) end
select #URL,SUBSTRING(#URL,CHARINDEX('?id=',#URL)+4,99)
Both examples are in there, comment either one to see result