I have a contact number field which stores number as
countrycode + ' ' + phonenumber..
Now i want to strip leading zeroes from phone number
I tried using
UPDATE [dbo].[User]
SET PhoneNumber = REPLACE(LTRIM(REPLACE([PhoneNumber], '0', ' ')), ' ', '0')
but this replaces the space in between with '0'
Any suggestions?
Try converting the value to int or numeric
Eg:
select '91 004563' as Input, CONVERT(INT, SUBSTRING('91 004563',CHARINDEX(' ','91 004563')+1,100)) as Output
This gives the result
Input Output
--------- ------
91 004563 4563
Try this: SUBSTRING(PhoneNumber, PATINDEX('%[^0 ]%', PhoneNumber + ' '), LEN(PhoneNumber))
Try:
declare #PhoneNumber varchar(max) = '00000000000000000000001200000031'
while substring(#PhoneNumber,1,1)='0'
begin
set #PhoneNumber = SUBSTRING(#PhoneNumber,2,LEN(#PhoneNumber))
end
select #PhoneNumber
Addressing your comment:
declare #PhoneNumber varchar(max) = '91 00000000000000000000001200000031'
declare #tempphn varchar(max) = substring(#PhoneNumber,4,len(#PhoneNumber) )
while substring(#tempphn,1,1)='0'
begin
set #tempphn = SUBSTRING(#tempphn,2,LEN(#tempphn))
end
select #tempphn
Related
I have sql table with the following values:
'test1 ', 'test2 '.
I need to delete all blank spaces in a string.
It looks easy but TRIM, LTRIM, RTRIM or REPLACE(column,' ','') does not work.
LEN() function count that space as a character.
Lenght of value 'test1 ' is 6.
In which way can I select that column without that blank space?
I need value 'test1'.
The minimal reproducible example is not provided.
Please try the following solution.
SQL
USE tempdb;
GO
DROP FUNCTION IF EXISTS dbo.udf_tokenize;
GO
/*
1. All invisible TAB, Carriage Return, and Line Feed characters will be replaced with spaces.
2. Then leading and trailing spaces are removed from the value.
3. Further, contiguous occurrences of more than one space will be replaced with a single space.
*/
CREATE FUNCTION dbo.udf_tokenize(#input VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN (SELECT CAST('<r><![CDATA[' + #input + ' ' + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)'));
END
GO
-- DDL and sample data population, start
DECLARE #mockTbl TABLE (ID INT IDENTITY(1,1), col_1 VARCHAR(100), col_2 VARCHAR(100));
INSERT INTO #mockTbl (col_1, col_2)
VALUES (' FL ', ' Miami')
, (' FL ', ' Fort Lauderdale ')
, (' NY ', ' New York ')
, (' NY ', '')
, (' NY ', NULL);
-- DDL and sample data population, end
-- before
SELECT * FROM #mockTbl;
-- remove invisible chars
UPDATE #mockTbl
SET col_1 = dbo.udf_tokenize(col_1)
, col_2 = dbo.udf_tokenize(col_2);
-- after
SELECT *, LEN(col_2) AS [col_2_len] FROM #mockTbl;
As discovered in the comments, the character(s) at the end of your value isn't a whitespace, it's a carriage return. LTRIM and RTRIM don't remove these characters, and TRIM only removes whitespace (character 32) by default.
If you want to remove some other characters, you can use TRIM, but you need to tell it to remove said other characters, using the TRIM({Characters} FROM {String}) syntax. The below removes leading and trailing Spaces (' '), Carriage Returns (CHAR(13)) and Line Breaks (CHAR(10)):
CREATE TABLE dbo.YourTable (SomeString varchar(50));
GO
INSERT INTO dbo.YourTable (SomeString)
VALUES('Trailing Space'),
('Trailing Line Break' + CHAR(10)),
('Trailing CRLF' + CHAR(13) + CHAR(10)),
('Trailing CRLF and spaces ' + CHAR(13) + CHAR(10) + ' ');
GO
DECLARE #TrimCharacters varchar(10) = ' ' + CHAR(13) + CHAR(10);
SELECT SomeString,
LEN(SomeString) AS Len,
DATALENGTH(SomeString) AS DataLength,
TRIM(SomeString) AS Trimmed,
DATALENGTH(TRIM(SomeString)) AS TrimmedDataLength,
TRIM(#TrimCharacters FROm SomeString) AS WellTrimmed,
DATALENGTH(TRIM(#TrimCharacters FROm SomeString)) AS WellTrimmedDataLength
FROM dbo.YourTable;
GO
DROP TABLE dbo.YourTable;
You can use the function below to check if each character of the string is within the ASCII values 32 to 126 (Numbers & Alphabet).
This will remove the "character" that's not within the ASCII range.
SQL:
DECLARE #TestString varchar(10) = 'test1 '
DECLARE #Result nvarchar(max)
SET #Result = ''
DECLARE #character nvarchar(1)
DECLARE #characterposition int
SET #characterposition = 1
WHILE #characterposition <= LEN(#TestString)
BEGIN
SET #character = SUBSTRING(#TestString , #characterposition, 1)
IF ASCII(#character) >= 32 AND ASCII(#character) <= 126
SET #Result = #Result + #character
SET #characterposition = #characterposition + 1
END
SELECT #Result
suppose i am having some unwanted characters in the data present in a column for eg name column in customers table has data like < ,is there anyway to modify such characters like '<' to blankspace while retrieving this data using select statement? This is to prevent xss scripts showing up due to old data which is having such unwanted characters
e.g:
select *
from customers
returns
Id Name Age city salary
-- ------ --- ---- ------
1 <hari 32 Ahmedabad 4000
2 Khilan 25 Delhi 5678
3 kaushik 23 Kota 234
i want <hari to be displayed as hari when this data is retrieved using select statement.How to achieve this ?
Something like...
SELECT REPLACE(REPLACE(a.name,'<', ''), '>','')
FROM ...
It may be better to write a function to remove special characters. Here the function replaces any character that does not look like a-z,A-Z(if case sensitive),0-9 and Space. You can add more if needed.
For example if you want to retain period(.) the use '[^a-zA-Z0-9 .]'
Function:
CREATE FUNCTION ufn_RemoveSpecialCharacters
(
#String VARCHAR(500),
#Exclude VARCHAR(100),
#CollapseSpaces BIT
)
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE #StartString INT,
#EndString INT,
#FinalString VARCHAR(500),
#CurrentString CHAR(1),
#PreviousString CHAR(1)
SET #StartString = 1
SET #EndString = LEN(ISNULL(#String, ''))
WHILE #StartString <= #EndString
BEGIN
SET #CurrentString = SUBSTRING(#String, #StartString, 1)
SET #PreviousString = SUBSTRING(#String, #StartString-1, 1)
IF #CurrentString LIKE ISNULL(#Exclude,'[^a-zA-Z0-9 ]')
BEGIN
SET #CurrentString = ''
IF #CollapseSpaces = 1
SET #FinalString = CASE WHEN #PreviousString = CHAR(32) THEN ISNULL(#FinalString, '') ELSE ISNULL(#FinalString, '')+' ' END
END
ELSE
BEGIN
SET #FinalString = ISNULL(#FinalString, '') + #CurrentString
IF #CollapseSpaces = 1
BEGIN
SET #FinalString = REPLACE(#FinalString,' ',' ')
END
END
SET #StartString = #StartString + 1
END
--PRINT #String
RETURN LTRIM(RTRIM(#FinalString))
END
GO
Usage:
Does not collapse Spaces
SELECT dbo.ufn_RemoveSpecialCharacters('This #$%string has#$% special #$% characters and spaces))', '[^a-zA-Z0-9 ]', 0)
Collapses multiple Spaces
SELECT dbo.ufn_RemoveSpecialCharacters('This #$%string has#$% special #$% characters and spaces))', '[^a-zA-Z0-9 ]', 1)
Here is the example
SELECT Replace(Column Name, ' ', '') AS C
FROM Contacts
WHERE Replace(Column Name, ' ', '') LIKE 'whatever'
Hope this was helpful
I have csv file in SQL
#code varchar(10) = 'pc-shr,pqr,qzcx,rtde,rz-fg,kj-hl,jk_lm'
I tried
Convert(Varchar(10), #code) + CASE WHEN len(#code) >10 THEN '..etc' Else '' END [code]
but I want like this means to find last comma in a string and after that add ..etc
it should look like this
'pc-shr,pqr, ..etc'
Is this what you are looking for?
SET #code=
CASE WHEN LEN(#code) > 10
THEN SUBSTRING(#code, 0, 10) + ', etc...'
ELSE ''
END
The main problem i found that is your variable declaration i.e. #code varchar(10). It fixes its size to 10. You can try belwo :
Declare #code varchar(max) = 'pc-shr,pqr,qzcx,rtde,rz-fg,kj-hl,jk_lm';
IF LEN(#code) > 10
BEGIN
SET #code=SUBSTRING(#code, 0, 10) + ', etc...'
END
Query:
SQLFIDDLEExample
declare #code varchar(10) = 'pc-shr,pqr,qzcx,rtde,rz-fg,kj-hl,jk_lm'
select #code
--pc-shr,pqr
SELECT SUBSTRING(#code, 1, LEN(#code)-CHARINDEX (',' ,REVERSE(#code))) + '..etc'
--pc-shr..etc
Replacing right part of string where is last comma, if you want results like in your example increase size - varchar(11)
EDIT: you want this?
SELECT SUBSTRING(#code, 1, LEN(#code)-CHARINDEX (',' ,REVERSE(#code))+1) + '..etc'
--pc-shr,..etc
Last comma in a string #code varchar(10) is this pc-shr*,*pqr so I add ..etc to it
SELECT SUBSTRING(#code, 1, LEN(#code)-CHARINDEX (',' ,REVERSE(#code))+1) + '..etc '
+ SUBSTRING(#code, LEN(#code)-CHARINDEX (',' ,REVERSE(#code))+2,LEN(#code))
--pc-shr,..etc pqr
I am trying to convert varchar to bigint:
select convert(bigint, (select(Replace((select value from sometable), ' ', ''))))
Why is it giving error???
Error converting data type varchar to bigint.
thanks in advance
Update
This is part of query I am trying:
select top 1 *
into #tblTemp
from testTable
where Status = 0
order by Sno
declare #mobile varchar(50)
set #mobile = (select(Replace((select mobile from #tblTemp), ' ', '')))
--set #mobile = (select( Replace(' 9428017524', ' ', '')))
select convert(bigint, #mobile)
drop table #tblTemp
Try this
select convert(bigint, CASE WHEN ISNUMERIC(#mobile + 'e0') = 0
THEN 0 ELSE #mobile)
-- add this case statement to return only numeric values,
-- your query will fail for values like '123-415-6789', '(123)415-6789'
Check your mobile numbers data and see if there are any unexpected values in that column, you may have to replace '-' or '(' or ')' etc with ''.
SeLECT * FROM #tblTmp
WHERE ISNUMERIC(Replace(mobile, ' ', '') + 'e0') = 0;
I am not sure what your real string is but for safety you can check ISNUMERIC() before convertion.
DECLARE #mobile varchar(50)
SELECT #mobile = REPLACE(mobile, ' ','') --much simplified version
FROM #tblTemp
IF ISNUMERIC(#mobile)
SELECT CONVERT(bigint, #mobile)
ELSE
SELECT 0
Just by reading your queries, you don't need a temp table here at all. Everything can be done in a single query
SELECT TOP (1) CONVERT(bigint, CASE ISNUMERIC( REPLACE(mobile,' ','') )
WHEN 1 THEN REPLACE(mobile,' ','')
ELSE 0 END )
FROM testTable
WHERE Status = 0
ORDER By Sno
I am trying to unmangle a very old variable. It was a full name entered all in one field and is found in two separate tables. In most newer places the name is in three logical columns, first, middle, last. In these it is all together and I am trying to strip it out to first initial, last name. I found the following here and modified it:
http://dbaspot.com/sqlserver-programming/365656-find-last-word-string.html
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
SELECT #full_name = REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = ISNULL(
(right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1)))),
(right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
)
When I leave full_name there it works fine...returns J. Test. When I null it the default should be
J. Public but instead ends up as .. When I test each line separately they work. I tried COALESCE as well with the same results. Is this too many brackets for ISNULL or ????
You have problem with right(#full_name,1) + '. ', for example:
select null+'.'
gives you ..
Try to change your code using case as below:
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
DECLARE #final VARCHAR(20)
SELECT #full_name = null--REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = case
when #full_name is not null
then (right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1))))
else (right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
end
select #final