Function to remove set of character in SQL Server - sql

I have the following function to remove set of character from a given string:
ALTER function removalspchar(#Name varchar(30))
returns varchar(500)
As
Begin
declare #sub char(1)
while patindex('%[-:;&, ]%',#Name)>0
begin
set #sub=substring(#Name,patindex('%[-:;&, ]%',#Name),1)
set #Name = replace(#Name,#sub,'')
end
return #Name
End
select dbo.removalspchar('CORP - Sovereign & Public Finance')
But the ouput of the following function coming as : CORPSovereignPublicFina rather than CORPSovereignPublicFinance.
Can somebody let me know what I am doing incorrect or a better way to resolve this issue.

Perhaps, you should increase length of param (#Name varchar(30)) say (#Name varchar(100)).

Related

Is there any function which checks a mathematical expression and returns a valid number in SQL server?

I have the below code where im using ISnumeric function to check the validity of an expression to do the math in sql.
But if I use ISnumeric function here it returns 0 for both the two conditons listed below. I need some function or a method to identify a valid mathematical expression.
Is there any alternative for this one ?
Begin
DECLARE #rcnt as VARCHAR(100)
DECLARE #ncnt as VARCHAR(100)
--Condition1
SET #rcnt = '(5918800.000 / 4963400.000) * (Slaughter(1023))'
--Condition2
SET #ncnt = '(5997200.000 / 5059900.000) * (400000.000)'
Select ISNUMERIC(#rcnt) as validittcheck
Select ISNUMERIC(#ncnt ) as validittcheck
END
ISNUMERIC() is a check that a variable is a valid numeric datatype, not that the result of the evaluation of a string expression is a valid numeric value. Your values became non-numeric as soon as the first '(' was evaluated.
The only way I know to get the desired result is to use dynamic sql. Here is an example, notice I put the try catch in there because your Slaughter() function does not exist and an exception is raised, so return zero as it is not a number:
DECLARE #rcnt as NVARCHAR(100)
DECLARE #ncnt as NVARCHAR(100)
--Condition1
SET #rcnt = 'SELECT #Result=ISNUMERIC( (5918800.000 / 4963400.000) * (Slaughter(1023)) )'
--Condition2
SET #ncnt = 'SELECT #Result=ISNUMERIC( (5997200.000 / 5059900.000) * (400000.000) )'
DECLARE #ResultValue1 INT=0
DECLARE #ResultValue2 INT=0
DECLARE #ResultParam NVARCHAR(100)= '#Result int OUTPUT'
BEGIN TRY
EXEC sp_executesql #rcnt, #ResultParam, #Result=#ResultValue1 OUTPUT
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
EXEC sp_executesql #ncnt, #ResultParam, #Result=#ResultValue2 OUTPUT
END TRY
BEGIN CATCH
END CATCH
SELECT #ResultValue1
SELECT #ResultValue2

SQL Server : REPLACE function replace ' ' with ',' in string

I am using SQL Server 2012. My input string is
'data1''data2''data3''data4''data5'
I want output to be:
'data1','data2','data3','data4','data5'
I tried the following
DECLARE
#P_NAME VARCHAR(20),
#V_NAME_1 VARCHAR(20);
SET #P_NAME = 'E056''E056''E056''E056''E056'
SET #V_NAME_1 = REPLACE(#P_NAME,'''',''',''')
SELECT #V_NAME_1
but it does not return the expected output.
Please let me know what I am missing.
Thanks,
Amol
You need to increase the length of your VARCHAR, I've set it to 50 below. Little tweak to your SET statement too. I've changed the values for testing;
DECLARE
#P_NAME VARCHAR(50),
#V_NAME_1 VARCHAR(50);
SET #P_NAME='E056''E057''E058''E059''E060'
SET #V_NAME_1=''''+REPLACE(#P_NAME,'''',''',''')+''''
SELECT #V_NAME_1

User Defined Function to determine whether string contains a substring

I have this code which is currently returning 0 regardless if the string contains the substring or not. It should return 1 if the substring is found.
CREATE FUNCTION dbo.checkLetters (#MESSAGE VARCHAR)
RETURNS INTEGER
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE #value INTEGER;
IF #MESSAGE LIKE '%findMe%'
SET #value = 1
ELSE
SET #value = 0
RETURN #value
END;
I also tried using charindex in my IF statement to no avail. Am I missing something simple here?
Testing like so:
SELECT dbo.checkletters('dLHLd');
use (#MESSAGE VARCHAR(max)) as a input parameter. or instead of max specify the length, currently in your function it is only 1. That is the issue.
Modify your function as given below:
ALTER FUNCTION dbo.checkLetters (#MESSAGE VARCHAR(max))
RETURNS INTEGER
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE #value INTEGER;
DECLARE #ExpressionToFind VARCHAR(50)
SET #ExpressionToFind = 'findme'
IF #MESSAGE LIKE '%' + #ExpressionToFind + '%'
SET #value = 1
ELSE
SET #value = 0
RETURN #value
END;
The problem was in your input parameter.
Your function could be rewritten as:
CREATE FUNCTION dbo.checkLetters (#MESSAGE VARCHAR(MAX))
RETURNS BIT
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN CAST(CHARINDEX('findMe', #MESSAGE) AS BIT);
END
CHARINDEX will find position of #MESSAGE in given string and if it's higher than 1, it will output 1 (bit operator).

'TRIM' is not a recognized built-in function name

I have created simple function
create function TRIM(#data varchar(20)) returns varchar(100)
as
begin
declare #str varchar(20)
set #str = rtrim(ltrim(#data))
return #str
end
I am executing in the below way.
declare #s varchar(25)
set #s = ' Amru '
select TRIM(#s)
I am getting the following error.
Msg 195, Level 15, State 10, Line 3
'TRIM' is not a recognized built-in function name.
Could any one please help me find the issue?
//use RTrim instead of Trim sql 2008
RTrim(ColumnName)
like this
select RTrim(a.ContactName) + ' ' + RTrim(a.City) as Name_City from customers as a
declare #s varchar(25)
set #s = ' Amru '
select RTRIM(LTRIM(#s))
You can use this way also without schema :)
You need to use the Schema prefix when calling user defined functions. In your case this will most likely be "dbo".
Change your select statement to:
declare #s varchar(25)
set #s = ' Amru '
select dbo.TRIM(#s)
The error is that 'TRIM' is not a built-in function in SQL Server (as the error message suggests :) )
You can either wrap it with both LTRIM and RTRIM instead, or create your own TRIM function that does the same.
SQL server tries to parse TRIM as a built-in function. To call user-defined function you should put schema prefix in front of the function call. Try something like:
declare #s varchar(25)
set #s = ' Amru '
select dbo.TRIM(#s)
Since dbois a default schema prefix.
If you want to change your schema, declare the function as follow: (note the schema prefix in front of function name)
create function dbo.TRIM(#data varchar(20)) returns varchar(100)
as
begin
--function body
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
?