I have an sql column that is a string of 100 \'Y\' or \'N\' characters. For example:
YYNYNYYNNNYYNY...
What is the easiest way
Maybe something like this...
SELECT
LEN(REPLACE(ColumnName, 'N', '')) as NumberOfYs
FROM
SomeTable
The easiest way is by using Oracle function:
SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME
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
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.