Sql sever Replace function - sql

I have file Location in my table like
FileLocation :- "\Saurabh\Rahul\Saurabh\ABC.text"
I need to replace "Saurabh" with "Ramesh" but i need to replace first "Saurabh" word only not all the "saurabh" which is in the string.
i tried with
select REPLACE(FILELOCATION,'saurabh','Ramesh')
How can i achive ?

try this:
You can Use STUFF and CHARINDEX functions.
DECLARE #str varchar(100) = '\Saurabh\Rahul\Saurabh\ABC.text'
SELECT STUFF(#str, CHARINDEX('saurabh', #str), LEN('saurabh'), '')
OUTPUT:
\\Rahul\Saurabh\ABC.text

To replace only the first occurence of a word in a string you can write as:
DECLARE #FileLocation VARCHAR(MAX)
DECLARE #ReplaceSubString VARCHAR(MAX),#NewSubString VARCHAR(MAX)
SET #FileLocation = '\\Saurabh\Rahul\Saurabh\ABC.text'
SET #ReplaceSubString = 'Saurabh'
SET #NewSubString = 'Ramesh'
SELECT STUFF ( #FileLocation ,
CHARINDEX(#ReplaceSubString, #FileLocation) ,
Len(#ReplaceSubString) ,
#NewSubString
)
Demo

Related

How to trim chinese and japanses characters

SELECT LOWER(LTRIM(RTRIM(' 価格 '))) AS TrimmedString;
It gives ?? as output.
How to put it here in function:
Create OR ALTER Function dbo.udf_GetTrimAndLower (#input NVARCHAR(max))
Returns NVARCHAR(max)
AS
BEGIN
DECLARE #output NVARCHAR(max);
select #output = LOWER(LTRIM(RTRIM(#input)));
RETURN (#output);
END
Try using this. I've added extra spaces for display purpose.
You have to use the nvarchar data type.
SELECT LTRIM(RTRIM(N' 価格 ')) AS TrimmedString;

Apply filter on sql query conditionally

Lets say I have a parameter #Name in a Stored Procedure. I want to filter by this parameter only if it is not empty / null. In any other case I want to ignore the filter.
I came up with the following two solutions. For the sake of example let us consider only the case that parameter is empty.
select *
from MyTable
where (len(rtrim(ltrim(#Name))) > 0 and Name = #Name) or (len(rtrim(ltrim(#Name))) = 0)
and the second one
#query = 'select * from MyTable'
if (len(rtrim(ltrim(#Name))) > 0)
#query = #query + ' Name = #Name '
Both of the approaches are working as expected.
Which do you think is the most clean (in terms of code) and easily maintainable
Are there any other (better) alternatives.
Note: This question may also suit in Code Review, please comment if you think so, in order to migrate there
It can be simplified like this
select *
from MyTable
where Name = #Name or #Name = '' or #Name is null
or as mentioned in comments, use NULLIF to check for empty string then replace it with NULL then validate it against IS NULL
where (Name = #Name or nullif(#Name, '') is null)
You don't need to check for length, by default, sql server is trailing-spaces-sensitive (The only exception to this rule is when the right side of the LIKE predicate's expression contains trailing spaces, then the pad is not removed).
Take the code below.
DECLARE #Name=' '
IF(#Name='') SELECT 1 ELSE SELECT 0
If you run the above code above you will get a result of 1. In your case, you can drop the LTRIM and RTRIM and simply test for equality against an empty string literal.
select *
from MyTable
where ((#Name='' OR #Name IS NULL)OR(Name = #Name))
OR
IF(#Name='') SET #Name=NULL
select *
from MyTable
where (#Name IS NULL OR Name = #Name)
if you are working with dynamic sql in stored procedure try something like this . It is better to use different variables for main select query and dynamic where query which can be extended easily . using this approach it will be easy to maintain when you proc becomes lengthy.
declare #finalquery varchar(max)
declare #mainSelectquery nvarchar(500);
declare #whereCondtions varchar (1000);
declare #DateParam datetime
set #mainSelectquery=''
set #whereCondtions =''
set #finalquery =''
set #DateParam=getdate()
set #mainSelectquery = 'select * from tblOrders where 1=1 '
set #whereCondtions = ' and Order_site =''TSN'''
set #whereCondtions = #whereCondtions + ' AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)'
set #finalquery =( #mainSelectquery + #whereCondtions)
print #finalquery
---- You can further extend this by adding more where condition based on the parameter pass in stored proc
if (#OrderID !=0)
begin
set #whereCondtions = ' OrderID='+str ( #stateRefID )
end

'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

SQL Server: How do you remove punctuation from a field?

Any one know a good way to remove punctuation from a field in SQL Server?
I'm thinking
UPDATE tblMyTable SET FieldName = REPLACE(REPLACE(REPLACE(FieldName,',',''),'.',''),'''' ,'')
but it seems a bit tedious when I intend on removing a large number of different characters for example: !##$%^&*()<>:"
Thanks in advance
Ideally, you would do this in an application language such as C# + LINQ as mentioned above.
If you wanted to do it purely in T-SQL though, one way make things neater would be to firstly create a table that held all the punctuation you wanted to removed.
CREATE TABLE Punctuation
(
Symbol VARCHAR(1) NOT NULL
)
INSERT INTO Punctuation (Symbol) VALUES('''')
INSERT INTO Punctuation (Symbol) VALUES('-')
INSERT INTO Punctuation (Symbol) VALUES('.')
Next, you could create a function in SQL to remove all the punctuation symbols from an input string.
CREATE FUNCTION dbo.fn_RemovePunctuation
(
#InputString VARCHAR(500)
)
RETURNS VARCHAR(500)
AS
BEGIN
SELECT
#InputString = REPLACE(#InputString, P.Symbol, '')
FROM
Punctuation P
RETURN #InputString
END
GO
Then you can just call the function in your UPDATE statement
UPDATE tblMyTable SET FieldName = dbo.fn_RemovePunctuation(FieldName)
I wanted to avoid creating a table and wanted to remove everything except letters and digits.
DECLARE #p int
DECLARE #Result Varchar(250)
DECLARE #BadChars Varchar(12)
SELECT #BadChars = '%[^a-z0-9]%'
-- to leave spaces - SELECT #BadChars = '%[^a-z0-9] %'
SET #Result = #InStr
SET #P =PatIndex(#BadChars,#Result)
WHILE #p > 0 BEGIN
SELECT #Result = Left(#Result,#p-1) + Substring(#Result,#p+1,250)
SET #P =PatIndex(#BadChars,#Result)
END
I am proposing 2 solutions
Solution 1: Make a noise table and replace the noises with blank spaces
e.g.
DECLARE #String VARCHAR(MAX)
DECLARE #Noise TABLE(Noise VARCHAR(100),ReplaceChars VARCHAR(10))
SET #String = 'hello! how * > are % u (: . I am ok :). Oh nice!'
INSERT INTO #Noise(Noise,ReplaceChars)
SELECT '!',SPACE(1) UNION ALL SELECT '#',SPACE(1) UNION ALL
SELECT '#',SPACE(1) UNION ALL SELECT '$',SPACE(1) UNION ALL
SELECT '%',SPACE(1) UNION ALL SELECT '^',SPACE(1) UNION ALL
SELECT '&',SPACE(1) UNION ALL SELECT '*',SPACE(1) UNION ALL
SELECT '(',SPACE(1) UNION ALL SELECT ')',SPACE(1) UNION ALL
SELECT '{',SPACE(1) UNION ALL SELECT '}',SPACE(1) UNION ALL
SELECT '<',SPACE(1) UNION ALL SELECT '>',SPACE(1) UNION ALL
SELECT ':',SPACE(1)
SELECT #String = REPLACE(#String, Noise, ReplaceChars) FROM #Noise
SELECT #String Data
Solution 2: With a number table
DECLARE #String VARCHAR(MAX)
SET #String = 'hello! & how * > are % u (: . I am ok :). Oh nice!'
;with numbercte as
(
select 1 as rn
union all
select rn+1 from numbercte where rn<LEN(#String)
)
select REPLACE(FilteredData,' ',SPACE(1)) Data from
(select SUBSTRING(#String,rn,1)
from numbercte
where SUBSTRING(#String,rn,1) not in('!','*','>','<','%','(',')',':','!','&','#','#','$')
for xml path(''))X(FilteredData)
Output(Both the cases)
Data
hello how are u . I am ok . Oh nice
Note- I have just put some of the noises. You may need to put the noises that u need.
Hope this helps
You can use regular expressions in SQL Server - here is an article based on SQL 2005:
http://msdn.microsoft.com/en-us/magazine/cc163473.aspx
I'd wrap it in a simple scalar UDF so all string cleaning is in one place if it's needed again.
Then you can use it on INSERT too...
I took Ken MC's solution and made it into an function which can replace all punctuation with a given string:
----------------------------------------------------------------------------------------------------------------
-- This function replaces all punctuation in the given string with the "replaceWith" string
----------------------------------------------------------------------------------------------------------------
IF object_id('[dbo].[fnReplacePunctuation]') IS NOT NULL
BEGIN
DROP FUNCTION [dbo].[fnReplacePunctuation];
END;
GO
CREATE FUNCTION [dbo].[fnReplacePunctuation] (#string NVARCHAR(MAX), #replaceWith NVARCHAR(max))
RETURNS NVARCHAR(MAX)
BEGIN
DECLARE #Result Varchar(max) = #string;
DECLARE #BadChars Varchar(12) = '%[^a-z0-9]%'; -- to leave spaces - SELECT #BadChars = '%[^a-z0-9] %'
DECLARE #p int = PatIndex(#BadChars,#Result);
DECLARE #searchFrom INT;
DECLARE #indexOfPunct INT = #p;
WHILE #indexOfPunct > 0 BEGIN
SET #searchFrom = LEN(#Result) - #p;
SET #Result = Left(#Result, #p-1) + #replaceWith + Substring(#Result, #p+1,LEN(#Result));
SET #IndexOfPunct = PatIndex(#BadChars, substring(#Result, (LEN(#Result) - #SearchFrom)+1, LEN(#Result)));
SET #p = (LEN(#Result) - #searchFrom) + #indexOfPunct;
END
RETURN #Result;
END;
GO
-- example:
SELECT dbo.fnReplacePunctuation('This is, only, a tést-really..', '');
Output:
Thisisonlyatéstreally
If it's a one-off thing, I would use a C# + LINQ snippet in LINQPad to do the job with regular expressions.
It is quick and easy and you don't have to go through the process of setting up a CLR stored procedure and then cleaning up after yourself.
Can't you use PATINDEX to only include NUMBERS and LETTERS instead of trying to guess what punctuation might be in the field? (Not trying to be snarky, if I had the code ready, I'd share it...but this is what I'm looking for).
Seems like you need to create a custom function in order to avoid a giant list of replace functions in your queries - here's a good example:
http://www.codeproject.com/KB/database/SQLPhoneNumbersPart_2.aspx?display=Print

TSQL using a wildcard in a where clause with dynamic sql

It appears that using the LIKE in a condition with wildcards and a variable inside of dynamic sql doesn't work, although it doesn't give an error. Here's an example.
The column called code has values like A0B01C02,A0B02C2D05,A0B02C2D05, etc and I am trying to match on rows containing a subset like 'B1'. When I do this it works and returns results as expected.
set #sql='select * from table where code like ''%B01%'''
exec sp_executesql #sql
If I hardcode the value of the variable
set #code='B01'
and modify the sql statement to concatenate the quotes and wildcards:
set #sql='select * from table where code like ' +''''+ '%'+#code + '%' + ''''
exec sp_executesql #sql
This returns the results as expected, but I had to hard code the variable. However, when I need to make the match using a variable for B01 and that the variable is set with a select statement, I don't get any results returned. I define an nvarchar like this:
set #code=(select top 1 code from anotherTable where USERID=#PersonId)
I confirmed that the select statement above returns the expected code, however. There is no error, but the query is "executed successfully". Am I missing something in the syntax for the where clause?
You can find a discussion of this at http://ask.sqlservercentral.com/questions/275/dynamic-where-clause-how-can-i-use-a-variable-in-an-in-predicate/312#312
My answer was to do the Parse By Comma Function.
/*****************************************************************
**** Parse A Comma Delimited String Into A Table
*****************************************************************/
ALTER FUNCTION [dbo].[ParseByComma] (
#String VARCHAR(600) )
RETURNS #TblSubString TABLE
(
VarSubString VARCHAR(50)
)
AS
BEGIN
DECLARE #intPos INT,
#SubStr VARCHAR(50)
-- Remove All Spaces
SET #String = REPLACE(#String, ' ','')
-- Find The First Comma
SET #IntPos = CHARINDEX(',', #String)
-- Loop Until There Is Nothing Left Of #String
WHILE #IntPos > 0
BEGIN
-- Extract The String
SET #SubStr = SUBSTRING(#String, 0, #IntPos)
-- Insert The String Into The Table
INSERT INTO #TblSubString (VarSubString) VALUES (#SubStr)
-- Remove The String & Comma Separator From The Original
SET #String = SUBSTRING(#String, LEN(#SubStr) + 2, LEN(#String) - LEN(#SubStr) + 1)
-- Get The New Index To The String
SET #IntPos = CHARINDEX(',', #String)
END
-- Return The Last One
INSERT INTO #TblSubString (VarSubString) VALUES (#String)
RETURN
END
I do not have a SQL Server in front of me at the moment but I wonder if this syntax might work for you?
set #sql='SELECT * FROM table WHERE UPPER(code) LIKE ''%''||(UPPER(COALESCE('''||#code||''',code)))||''%'' '
exec sp_executesql #sql
Best regards,
Kevin