I am trying to replace the nth character in SQL Server. I tried with it using replace():
SELECT REPLACE(ABC,0,1) FROM XXX
In above code all zeros will be replaced with one, but I only want to change it in a particular position and sometimes that position can change.
use stuff
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
select STUFF(ABC, starting_index, 1, 'X') from XXX
"Here your int position to replace" is the position no just replace with any int no and that position will be replaced
Note : (Thanks to pcnate for suggestion)
starting_index is your int position to replace.
You're looking for STUFF:
select STUFF(ABC, #n, 1, 'X') from XXX
This would replace the #nth character with an X.
Technically it seeks into the original string at column ABC starting at position #n, deletes 1 character, then inserts the string 'X' at that position.
You use STUFF for this:
SELECT STUFF(ABC, 5, 1, '1')
FROM XXX
This would replace the 5th character with a 1.
Use stuff():
select stuff(abc, 0, 1, 'a')
It is documented here.
Use Stuff.
STUFF(Column_Name,starting_index,
lenth_ofthestring_to_replace_from_starting_index, character_to_replce)
Example_
DECLARE #str varchar(100) = '123456789'
select #str
SELECT STUFF(#str,2,1, 'hello')
-- want to replece 1 charter starting from 2nd position with the string 'hello'
Check this.
SELECT STUFF(#str,2,25, 'hello'),len(#str)
Related
I have a SQL query which includes the line:
WHERE
[TraceableItem].[IdentificationNo] LIKE N'015933%'
I would like this to match the following numbers:
015933
00015933
000000000015933
But not allow any non-zero characters. How could I do this?
--Some test data
DECLARE #sample TABLE
(
number_as_string VARCHAR(20)
)
INSERT INTO #sample
VALUES
('015933') -- okay
,('00015933') -- okay
,('000000000015933')-- okay
,(' 00015933') -- dont return as this doesnt start with a 0
,('25') -- dont return wrong number
,('string') -- dont return as its a string
,('st15933') -- dont return as it starts with a string.
,('001000015933') -- dont return as this is the number 1000015933
SELECT
*
FROM
#sample as s
WHERE
--only consider rows that are a number
--stops CONVERT exception being thrown on lines that do no convert
ISNUMERIC(s.number_as_string) = 1
AND
--Convert to INT wipes out the leading 0's, but also spaces
CONVERT(INT,s.number_as_string) LIKE '15933%'
AND
--must start with a number, i.e. check it doesn't start with a space.
--LEFT(s.number_as_string,1) NOT LIKE '[^0-9]'
--This version is easier to read as its not a double NOT logic like the version above
--Thanks to #Robert Kock
LEFT(s.number_as_string,1) BETWEEN '0' AND '9'
Gives the result
number_as_string
----------------
015933
00015933
000000000015933
You probably want to first convert to int and back to string as suggested by Neeraj Agarwal. But then take the left five characters and compare for exact equality to '15933'
where '15933' = left(convert(varchar(50),convert(int,
TraceableItem.IdentificationNo
)),5)
You can see it at work in the sample below, where it captures everything you desire and a little more, but doesn't capture the case presented by Harry Adams in the comments to Neeraj.
select *
from (values
('015933'),
('00015933'),
('000000000015933'),
('0001593399'),
('15933'),
('001000015933')
) vals (v)
where '15933' = left(convert(varchar(50),convert(int, v)),5)
I don't like converting to a number for this purpose. But one method is to "trim" the leading zeros away. For an exact match:
where replace(ltrim(replace([TraceableItem].[IdentificationNo], '0', ' ')), ' ', '0') = '15933'
For LIKE:
where replace(ltrim(replace([TraceableItem].[IdentificationNo], '0', ' ')), ' ', '0') LIKE '15933%'
You can also express this with LIKE/NOT LIKE:
where TraceableItem].[IdentificationNo] like '%15933%' and
TraceableItem].[IdentificationNo] not like '%[^0]%15933%'
You can use cast to convert to an int and back to a character string provided the string consists of digits only, e.g.:
select cast(cast("00015933" as int) as varchar(24))
Hi I have one doubt in sql server .
how to get first position to right side specific character position.
table : empfiles
filename:
ab_re_uk_u_20101001
ax_by_us_19991001
abc_20181002
I want output like below:
filename
ab_re_uk_u
ax_by_us
abc
I tried like below :
select SUBSTRING(filename,1,CHARINDEX('2',filename) - 1) as filename from empfiles
above query is not given expected result please tell me how to write query to achive this task in sql server .
If last position has always numeric values then you can use patindex():
select *, substring(filename, 1, patindex('%[0-9]%', filename)-2) as NewFile
from empfiles e;
If you want to get characters after than _ to right sight of string then you can use combo to reverse() and substring()
select *,
reverse(substring(reverse(filename),charindex('_', reverse(filename))+1, len(filename)))
from empfiles e;
Another way is to use reverse in combination with STUFF.
create table f(filename nvarchar(100));
insert into f values
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
select
filename=reverse(stuff(reverse(filename),1,charindex('_',reverse(filename)),''))
from f
Try This
CREATE TABLE #DATA([FILENAME] NVARCHAR(100));
INSERT INTO #DATA VALUES
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
SELECT [filename],
SUBSTRING([filename],0,PATINDEX('%[0-9]%',[filename])-1) AS ExpectedResult
FROM #Data
Result
filename ExpectedResult
--------------------------------------
ab_re_uk_u_20101001 ab_re_uk_u
ax_by_us_19991001 ax_by_us
abc_20181002 abc
Well, obviously the last position value is a date, and the format is YYYYMMDD so its 8 characters, plus, added by underscore character, so that makes its 9 character.
Assumed by the above statement applied, the following logic of the query should work
SELECT SUBSTRING(ColumnText, 1, LEN(ColumnText) - 9)
Which means, only display characters from character position 1, to character position LEN - 9, which LEN is the length of characters, and 9 is the last 9 digit of number to be removed
Try with this ..
select [filename],SUBSTRING([filename],1,PATINDEX('%_[0-9]%',[filename])-1) from empfiles
Individual Select records
SELECT SUBSTRING('ab_re_uk_u_20101001',1,PATINDEX('%_[0-9]%','ab_re_uk_u_20101001')-1)
SELECT SUBSTRING('ax_by_us_19991001',1,PATINDEX('%_[0-9]%','ax_by_us_19991001')-1)
SELECT SUBSTRING('abc_20181002',1,PATINDEX('%_[0-9]%','abc_20181002')-1)
I have a string which is in 99999 124 fdsg format.
I want to replace the first space with - and the next space with a non-space. My expected result will look like this:
99999-124fdsg
To replace the first char I used this expression:
stuff(Product,charindex('',product),1,'-')as trim
Because I want to name the new column as trim. How can I do for the second character?
Charindex has last parameter start_location use it to search for second empty string
Try this
DECLARE #str VARCHAR(50) = '99999 124 fdsg'
SELECT Stuff(Stuff(#str,Charindex(' ',#str),1,'-'),Charindex(' ',#str,Charindex(' ',#str) + 1),1,'')
Result : 99999-124fdsg
Assuming, that you example with STUFF works correctly for the first blank you can just wrap this with REPLACE. After STUFF there's only the other blank left:
replace(stuff(Product,charindex(' ',product),1,'-'),' ','')
Working example:
DECLARE #s VARCHAR(50) = '99999 124 fdsg';
select replace(stuff(#s,charindex(' ',#s),1,'-'),' ','')
The result
99999-124fdsg
I want to Replace a particular character on position 4 in sql Server ,
i know about replace or case when but my problem is that i just want to 4th position character replace ,
i am trying like
SELECT REPLACE(_NAME,0,1) AS exp FROM _EMPLOYEE
but it will not cheching 4th character
for example if _name contain IMR002001 then it should be IMR012001
Use stuff():
select stuff(_NAME, 4, 1, '#')
This replaces the substring starting at position 4 with length 1 with the string that is the fourth argument. The string can be longer or shorter than the string being replaced.
For your example:
select stuff(_NAME, 4, 1, '1')
Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'