How to remove character from an SQL query in where condition - sql

I got some dirty database of SQL to do a task. I have a column which can have data from different format like the following:
format 1 = 0000-0000000
format 2 = 0000.0000000
format 3 = 00000000000
The format 3 is a good format for my query.
$sql = "SELECT * from table where col='00000000000'"
I want to to remove these character in select query without disturbing the actual data.

Seems you need Replace function. Just remove extra symbols during comparison
SELECT * from table
where replace(replace(col, '-', ''), '.', '') ='00000000000'

There is a function to format the string:
create FUNCTION [dbo].[fn_StripString](#value as varchar(80), #KeepValues as varchar(80))
RETURNS varchar(80)
AS
begin
While PatIndex(#KeepValues, #value) > 0
Set #value = Stuff(#Valor, PatIndex(#KeepValues, #value), 1, '')
return #value
end
Then, assuming you just want numeric values:
SELECT *
from table
where dbo.fn_StripString(col, '%[^0-9]%') = '00000000000'

Use IN query
Select * from table where col in ('00000000000','0000.0000000','0000-0000000')

Related

Is there a way to find default values that is a combination of the same number like 000/000/0 or 11111 or 99999?

I want to find values in the SQL database that is a combination of the same number such as 0000 or 000/000/0 or 11111 or 99999 etc.
Is there a way to find these values without hardcoding?
What I am currently doing is:
select * from XXXX where value = '000/000/0'
A simple solution is to remove all instances of first character of the string, and check if the result is an empty string:
select *
from t
where replace(replace(str, '/', ''), substring(str, 1, 1), '') = ''
Try this on :
SELECT *
FROM XXXX
WHERE value IN ('000/000/0',11111,99999,0000)
If you need fill column values with application or other third-party. you can use stored procedure like below:
CREATE PROC dbo.usp_ListOfNumbers #NumberValues Nvarchar(200)
as
BEGIN
SELECT *
FROM XXXX
WHERE value = #NumberValues
END
for call just use
EXEC dbo.usp_ListOfNumbers #NumberValues = '000/000/0'

Sql Where Clause not working if add space at the end of string

I have below sql Query
Select * from usertable where username = 'xyz (space)';
It is giving me the result which is wrong the result has to come only when i not add space at end because in database there is no space.
Is there any function or how can i do that.
I hope you want to filter the records those have the space in the last position.
DECLARE #TestTable TABLE (Data VARCHAR(20));
INSERT INTO #TestTable (Data) VALUES ('xyz'), ('Sharma ');
SELECT * FROM #TestTable WHERE Data = 'Sharma ';
SELECT * FROM #TestTable WHERE Data = 'Sharma';
you will get the same result for WHERE Data = 'Sharma ' and 'Sharma'
Using SUBSTRING(Data, DATALENGTH(Data), 1) you can get the last character of the column and add the condition in WHERE clause will solve your problem:
DECLARE #TestingValue AS VARCHAR(20) = 'Sharma'; -- 'xyz' -- 'Sharma '
SELECT * FROM #TestTable WHERE Data = #TestingValue AND SUBSTRING(#TestingValue, DATALENGTH(#TestingValue), 1) = ' ' ;
The above block return result if you set 'Sharma ' as parameter value.
This is because SQL Server follows ANSI 92 rules which stipulates that:
SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, <Comparison Predicate>, General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.
(my emphasis)
If the data is CHAR data with trailing spaces you could use the RTRIM function like this;
select * from usertable where RTRIM(username) = 'xyz'
EDIT: In order to match including trailing spaces you can use the DATALENGTH function, like this;
select * from usertable where username = 'xyz ' AND
DATALENGTH(username) = DATALENGTH('xyz ')
If you don't want the result if there is space at end you can use below query
select * from usertable where username not like '% '
Or this one:
select * from usertable where right(username,1) <> ' '
Hi this code works for me........
select * from usertable where username = 'xyz (Space) ' AND
DATALENGTH(username) = DATALENGTH('xyz (Space) ')

How to remove the first character if it is a specific character in SQL

I currently have a table Telephone it has entries like the following:
9073456789101
+773456789101
0773456789101
What I want to do is remove only the 9 from the start of all the entries that have a 9 there but leave the others as they are.
any help would be greatly appreciated.
While all other answer are probably also working, I'd suggest to try and use STUFF function to easily replace a part of the string.
UPDATE Telephone
SET number = STUFF(number,1,1,'')
WHERE number LIKE '9%'
SQLFiddle DEMO
Here is the code and a SQLFiddle
SELECT CASE
WHEN substring(telephone_number, 1, 1) <> '9'
THEN telephone_number
ELSE substring(telephone_number, 2, LEN(telephone_number))
END
FROM Telephone
Update Telephone set number = RIGHT(number,LEN(number)-1) WHERE number LIKE '9%';
I recently solved a similar problem with a combination of RIGHT(), LEN() & PATINDEX(). PATINDEX will return the integer 1 when it finds a 9 as the first character and 0 otherwise. This method allows all records to be returned at once without a CASE WHEN statement.
SELECT
RIGHT(number, LEN(number) - PATINDEX('9%', number))
FROM Telephone
UPDATE dbo.Telephone
SET column_name = SUBSTRING(column_name, 2, 255)
WHERE column_name LIKE '9%';
Stuff is a great function for this. However, using it with an update statement with a where clause is great, but what if I was doing an insert, and I needed all of the rows inserted in one pass. The below will remove the first character if it is a period, does not use the slower case statement, and converts nulls to an empty string.
DECLARE #Attachment varchar(6) = '.GIF',
#Attachment2 varchar(6)
SELECT
#Attachment2 = ISNULL(ISNULL(NULLIF(LEFT(#Attachment, 1), '.'), '') + STUFF(#Attachment, 1, 1, ''), '')
SELECT
#Attachment2
DECLARE #STR nvarchar(200) = 'TEST'
SET #STR = STUFF(#STR,1,1,'')
PRINT #STR
Result will be "EST"
You can use replace in select statement instead of where or update
SELECT REPLACE(REPLACE('_'+number,'_9',''),'_','') FROM #tbl

How to count instances of character in SQL Column

I have an sql column that is a string of 100 'Y' or 'N' characters. For example:
YYNYNYYNNNYYNY...
What is the easiest way to get the count of all 'Y' symbols in each row.
This snippet works in the specific situation where you have a boolean: it answers "how many non-Ns are there?".
SELECT LEN(REPLACE(col, 'N', ''))
If, in a different situation, you were actually trying to count the occurrences of a certain character (for example 'Y') in any given string, use this:
SELECT LEN(col) - LEN(REPLACE(col, 'Y', ''))
In SQL Server:
SELECT LEN(REPLACE(myColumn, 'N', ''))
FROM ...
This gave me accurate results every time...
This is in my Stripes field...
Yellow, Yellow, Yellow, Yellow, Yellow, Yellow, Black, Yellow, Yellow, Red, Yellow, Yellow, Yellow, Black
11 Yellows
2 Black
1 Red
SELECT (LEN(Stripes) - LEN(REPLACE(Stripes, 'Red', ''))) / LEN('Red')
FROM t_Contacts
DECLARE #StringToFind VARCHAR(100) = "Text To Count"
SELECT (LEN([Field To Search]) - LEN(REPLACE([Field To Search],#StringToFind,'')))/COALESCE(NULLIF(LEN(#StringToFind), 0), 1) --protect division from zero
FROM [Table To Search]
This will return number of occurance of N
select ColumnName, LEN(ColumnName)- LEN(REPLACE(ColumnName, 'N', ''))
from Table
The easiest way is by using Oracle function:
SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME
Maybe something like this...
SELECT
LEN(REPLACE(ColumnName, 'N', '')) as NumberOfYs
FROM
SomeTable
Below solution help to find out no of character present from a string with a limitation:
1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and
wrong output in below condition:
SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --Correct
SELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --Wrong
SELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong
2) Try with below solution for correct output:
Create a function and also modify as per requirement.
And call function as per below
select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correct
select dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
#string nvarchar(500),
#find_char char(1)
)
RETURNS integer
AS
BEGIN
-- Declare the return variable here
DECLARE #total_char int; DECLARE #position INT;
SET #total_char=0; set #position = 1;
-- Add the T-SQL statements to compute the return value here
if LEN(#string)>0
BEGIN
WHILE #position <= LEN(#string) -1
BEGIN
if SUBSTRING(#string, #position, 1) = #find_char
BEGIN
SET #total_char+= 1;
END
SET #position+= 1;
END
END;
-- Return the result of the function
RETURN #total_char;
END
GO
try this
declare #v varchar(250) = 'test.a,1 ;hheuw-20;'
-- LF ;
select len(replace(#v,';','11'))-len(#v)
If you want to count the number of instances of strings with more than a single character, you can either use the previous solution with regex, or this solution uses STRING_SPLIT, which I believe was introduced in SQL Server 2016. Also you’ll need compatibility level 130 and higher.
ALTER DATABASE [database_name] SET COMPATIBILITY_LEVEL = 130
.
--some data
DECLARE #table TABLE (col varchar(500))
INSERT INTO #table SELECT 'whaCHAR(10)teverCHAR(10)whateverCHAR(10)'
INSERT INTO #table SELECT 'whaCHAR(10)teverwhateverCHAR(10)'
INSERT INTO #table SELECT 'whaCHAR(10)teverCHAR(10)whateverCHAR(10)~'
--string to find
DECLARE #string varchar(100) = 'CHAR(10)'
--select
SELECT
col
, (SELECT COUNT(*) - 1 FROM STRING_SPLIT (REPLACE(REPLACE(col, '~', ''), 'CHAR(10)', '~'), '~')) AS 'NumberOfBreaks'
FROM #table
The second answer provided by nickf is very clever. However, it only works for a character length of the target sub-string of 1 and ignores spaces. Specifically, there were two leading spaces in my data, which SQL helpfully removes (I didn't know this) when all the characters on the right-hand-side are removed. Which meant that
" John Smith"
generated 12 using Nickf's method, whereas:
" Joe Bloggs, John Smith"
generated 10, and
" Joe Bloggs, John Smith, John Smith"
Generated 20.
I've therefore modified the solution slightly to the following, which works for me:
Select (len(replace(Sales_Reps,' ',''))- len(replace((replace(Sales_Reps, ' ','')),'JohnSmith','')))/9 as Count_JS
I'm sure someone can think of a better way of doing it!
You can also Try This
-- DECLARE field because your table type may be text
DECLARE #mmRxClaim nvarchar(MAX)
-- Getting Value from table
SELECT top (1) #mmRxClaim = mRxClaim FROM RxClaim WHERE rxclaimid_PK =362
-- Main String Value
SELECT #mmRxClaim AS MainStringValue
-- Count Multiple Character for this number of space will be number of character
SELECT LEN(#mmRxClaim) - LEN(REPLACE(#mmRxClaim, 'GS', ' ')) AS CountMultipleCharacter
-- Count Single Character for this number of space will be one
SELECT LEN(#mmRxClaim) - LEN(REPLACE(#mmRxClaim, 'G', '')) AS CountSingleCharacter
Output:
If you need to count the char in a string with more then 2 kinds of chars, you can use instead of 'n' - some operator or regex of the chars accept the char you need.
SELECT LEN(REPLACE(col, 'N', ''))
Try this:
SELECT COUNT(DECODE(SUBSTR(UPPER(:main_string),rownum,LENGTH(:search_char)),UPPER(:search_char),1)) search_char_count
FROM DUAL
connect by rownum <= length(:main_string);
It determines the number of single character occurrences as well as the sub-string occurrences in main string.
Here's what I used in Oracle SQL to see if someone was passing a correctly formatted phone number:
WHERE REPLACE(TRANSLATE('555-555-1212','0123456789-','00000000000'),'0','') IS NULL AND
LENGTH(REPLACE(TRANSLATE('555-555-1212','0123456789','0000000000'),'0','')) = 2
The first part checks to see if the phone number has only numbers and the hyphen and the second part checks to see that the phone number has only two hyphens.
for example to calculate the count instances of character (a) in SQL Column ->name is column name
'' ( and in doblequote's is empty i am replace a with nocharecter #'')
select len(name)- len(replace(name,'a','')) from TESTING
select len('YYNYNYYNNNYYNY')- len(replace('YYNYNYYNNNYYNY','y',''))
DECLARE #char NVARCHAR(50);
DECLARE #counter INT = 0;
DECLARE #i INT = 1;
DECLARE #search NVARCHAR(10) = 'Y'
SET #char = N'YYNYNYYNNNYYNY';
WHILE #i <= LEN(#char)
BEGIN
IF SUBSTRING(#char, #i, 1) = #search
SET #counter += 1;
SET #i += 1;
END;
SELECT #counter;

Removing leading zeroes from a field in a SQL statement

I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.
Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')
You can use this:
SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')
I had the same need and used this:
select
case
when left(column,1) = '0'
then right(column, (len(column)-1))
else column
end
select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20),
patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'),
20)), 20)
returns N0Z, that is, will get rid of leading zeroes and anything that comes before them.
If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:
select CASE
WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
THEN '0'
ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
END
In case you want to remove the leading zeros from a string with a unknown size.
You may consider using the STUFF command.
Here is an example of how it would work.
SELECT ISNULL(STUFF(ColumnName
,1
,patindex('%[^0]%',ColumnName)-1
,'')
,REPLACE(ColumnName,'0','')
)
See in fiddler various scenarios it will cover
https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=14c2dca84aa28f2a7a1fac59c9412d48
You can try this - it takes special care to only remove leading zeroes if needed:
DECLARE #LeadingZeros VARCHAR(10) ='-000987000'
SET #LeadingZeros =
CASE WHEN PATINDEX('%-0', #LeadingZeros) = 1 THEN
#LeadingZeros
ELSE
CAST(CAST(#LeadingZeros AS INT) AS VARCHAR(10))
END
SELECT #LeadingZeros
Or you can simply call
CAST(CAST(#LeadingZeros AS INT) AS VARCHAR(10))
Here is the SQL scalar value function that removes leading zeros from string:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Vikas Patel
-- Create date: 01/31/2019
-- Description: Remove leading zeros from string
-- =============================================
CREATE FUNCTION dbo.funRemoveLeadingZeros
(
-- Add the parameters for the function here
#Input varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #Result varchar(max)
-- Add the T-SQL statements to compute the return value here
SET #Result = #Input
WHILE LEFT(#Result, 1) = '0'
BEGIN
SET #Result = SUBSTRING(#Result, 2, LEN(#Result) - 1)
END
-- Return the result of the function
RETURN #Result
END
GO
To remove the leading 0 from month following statement will definitely work.
SELECT replace(left(Convert(nvarchar,GETDATE(),101),2),'0','')+RIGHT(Convert(nvarchar,GETDATE(),101),8)
Just Replace GETDATE() with the date field of your Table.
To remove leading 0, You can multiply number column with 1
Eg: Select (ColumnName * 1)
select CASE
WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
THEN ''
ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
END
you can try this
SELECT REPLACE(columnname,'0','') FROM table
I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.
CASE
WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))
WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))
WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))
ELSE
END
select ltrim('000045', '0') from dual;
LTRIM
-----
45
This should do.