Replacing any String that contains "00" or "0" with 00 or 0 (Handling double quotes in SQL Server) - sql

My output in a column currently has:
Pill Type
"00" Vegetarian Capsules : (
"0" Vegetarian Capsules : (
"0" Gelatin Capsules : (
"DINO" : (
I need to replace the entire string with only what is contained between the double quotes, with this being my desired result:
Pill Type
00
0
0
DINO
I'm newer to SQL and before would get by doing a CASE statement or even a nested REPLACE() statement to clean up some strings
Now that there are double quotes, too many phrases that would take a long time to write out replacing each one, and needing only what is contained within the double quotes has me stuck and I can't quite figure out a solution.

Here's a script that demonstrates how you can get the desired result:
declare #tmp as table (s nvarchar(100) not null);
insert into #tmp values ('"00" Vegetarian Capsules : (');
insert into #tmp values ('"0" Vegetarian Capsules : (');
insert into #tmp values ('"0" Gelatin Capsules : (');
insert into #tmp values ('"DINO" : (');
select SUBSTRING(s, charindex('"', s) + 1, len(s) - charindex('"', reverse(s)) - charindex('"', s)) from #tmp;
However, please be aware that the entire string is the result if no double quote is present. You may use a CASE expression if you need to address this.

Related

In SQL Server, how can I search for column with 1 or 2 whitespace characters?

So I need to filter column which contains either one, two or three whitespace character.
CREATE TABLE a
(
[col] [char](3) NULL,
)
and some inserts like
INSERT INTO a VALUES (' ',' ', ' ')
How do I get only the row with one white space?
Simply writing
SELECT *
FROM a
WHERE column = ' '
returns all rows irrespective of one or more whitespace character.
Is there a way to escape the space? Or search for specific number of whitespaces in column? Regex?
Use like clause - eg where column like '%[ ]%'
the brackets are important, like clauses provide a very limited version of regex. If its not enough, you can add a regex function written in C# to the DB and use that to check each row, but it won't be indexed and thus will be very slow.
The other alternative, if you need speed, is to look into full text search indexes.
Here is one approach you can take:
DECLARE #data table ( txt varchar(50), val varchar(50) );
INSERT INTO #data VALUES ( 'One Space', ' ' ), ( 'Two Spaces', ' ' ), ( 'Three Spaces', ' ' );
;WITH cte AS (
SELECT
txt,
DATALENGTH ( val ) - ( DATALENGTH ( REPLACE ( val, ' ', '' ) ) ) AS CharCount
FROM #data
)
SELECT * FROM cte WHERE CharCount = 1;
RETURNS
+-----------+-----------+
| txt | CharCount |
+-----------+-----------+
| One Space | 1 |
+-----------+-----------+
You need to use DATALENGTH as LEN ignores trailing blank spaces, but this is a method I have used before.
NOTE:
This example assumes the use of a varchar column.
Trailing spaces are often ignored in string comparisons in SQL Server. They are treated as significant on the LHS of the LIKE though.
To search for values that are exactly one space you can use
select *
from a
where ' ' LIKE col AND col = ' '
/*The second predicate is required in case col contains % or _ and for index seek*/
Note with your example table all the values will be padded out to three characters with trailing spaces anyway though. You would need a variable length datatype (varchar/nvarchar) to avoid this.
The advantage this has over checking value + DATALENGTH is that it is agnostic to how many bytes per character the string is using (dependant on datatype and collation)
DB Fiddle
How to get only rows with one space?
SELECT *
FROM a
WHERE col LIKE SPACE(1) AND col NOT LIKE SPACE(2)
;
Though this will only work for variable length datatypes.
Thanks guys for answering.
So I converted the char(3) column to varchar(3).
This seemed to work for me. It seems sql server has ansi padding that puts three while space in char(3) column for any empty or single space input. So any search or len or replace will take the padded value.

Trim "-" from data returned from SQL Server

I have a query that in SQL Server that returns data like this:
1234-A
2345-BB
3456-C
5678-CC
4567-AA
6789-B
01234-A
26857-ZZ
This is what I need it display:
A
B
C
C
A
B
A
Z
I need to get the first letter behind the '-'. How do I get this to display?
Try this:
DECLARE #MyTable TABLE (MyCol VARCHAR(255));
INSERT #MyTable (MyCol)
VALUES ('1234-A'),('2345-BB'),('3456-C'),('5678-CC'),
('4567-AA'),('6789-B'),('01234-A'),('26857-ZZ');
SELECT SUBSTRING(MyCol, CHARINDEX('-', MyCol, 1) + 1, 1)
FROM #MyTable;
CHARINDEX finds where the '-' in the column value is.
SUBSTRING starts at that index + 1 and returns, in this case, 1 character.
You can use substr In conjunction with instr to get the output

Split strings at specified character in SQL

I need to split a string in SQL at a specified character. I need to split TEX_TEXT field at the '(' character. I use it this way, but in the result the '(' is there.
Left(TEX_TEXT, CHARINDEX('(', TEX_TEXT ) ) as GroupName,
I need the result without the '(' charcter, like this: 80, 80 Avant and so on.... Thanks in advance!
try this demo. Using IIF, LEFT and CHARINDEX
declare #mytable table (col1 varchar(20))
insert into #mytable
values ('80 (xxx 123)'),('79'),('100 Avant (d1)')
SELECT
LEFT(col1,
iif(
CHARINDEX('(', col1) -- get location of 'C'
= 0, -- if charindex is 0 then get length of the string
LEN(col1), -- thus this, if you don't check for no '(' then using charindex will return an error
CHARINDEX('(', col1) - 1) -- otherwise get the location of '(' minus 1
)
FROM #mytable
result
80
79
100 Avant
The easiest thing to do is wrap it in a REPLACE() function. As you are splitting and taking the first part you can be sure there will only ever be one occurrence of the opening parenthesis.
REPLACE(Left(TEX_TEXT, CHARINDEX('(', TEX_TEXT ) ), '(', '') as GroupName
Last thing to do is RTRIM the whole lot to ensure there are no trailing spaces.
The best part to this approach is that you don't need to test the data before applying logic so it should work quicker than using an IIf statement

Teradata : Sum up values in a column

Problem Statement
Example is shown in below image :
The last 2 rows have the patterns like "1.283 2 3" in a single cell. The numbers are seperated by space in the column. We need to add those nos and represent in the format given in Output.
So, the cell having "1.283 2 3" must be converted to 6.283
Challenges facing :
The column values are in string format.
Add nos after casting them into integer
Donot want to take data in UNIX box and manipulate the same.
In TD14 there would be a built-in table UDF named STRTOK_SPLIT_TO_TABLE, before you need to implement your own UDF or use a recursive query.
I modified an existing string splitting script to use blanks as delimiter:
CREATE VOLATILE TABLE Strings
(
groupcol INT NOT NULL,
string VARCHAR(991) NOT NULL
) ON COMMIT PRESERVE ROWS;
INSERT INTO Strings VALUES (1,'71.792');
INSERT INTO Strings VALUES (2,'71.792 1 2');
INSERT INTO Strings VALUES (3,'1.283 2 3');
WITH RECURSIVE cte
(groupcol,
--string,
len,
remaining,
word,
pos
) AS (
SELECT
GroupCol,
--String,
POSITION(' ' IN String || ' ') - 1 AS len,
TRIM(LEADING FROM SUBSTRING(String || ' ' FROM len + 2)) AS remaining,
TRIM(SUBSTRING(String FROM 1 FOR len)) AS word,
1
FROM strings
UNION ALL
SELECT
GroupCol,
--String,
POSITION(' ' IN remaining)- 1 AS len_new,
TRIM(LEADING FROM SUBSTRING(remaining FROM len_new + 2)),
TRIM(SUBSTRING(remaining FROM 1 FOR len_new)),
pos + 1
FROM cte
WHERE remaining <> ''
)
SELECT
groupcol,
-- remove the NULLIF to get 0 for blank strings
SUM(CAST(NULLIF(word, '') AS DECIMAL(18,3)))
FROM cte
GROUP BY 1
This might use a lot of spool, hopefully you're not running that on a large table.

How to extract the text from a sql column

I have a pattern in a column in sql table ..
IF PAIRING IS NOT SUCCESSFUL,
REPEAT THE PAIRING PROCESS.
IF PAIRING IS STILL NOT SUCCESSFUL, REPLACE THE MOTOR.
I wish to extract the text "PAIRING IS STILL NOT SUCCESSFUL". The text after second if ". IF" before "," and also the text after the comma has to be either REPLACE or REPAIR or TEST..
I tried this way..
SUBSTRING( TextName,(PATINDEX('%. IF%,%', TextName) + 9), 20)
The third part of the substring is currently hardcoded, but how to genarlize the query.
Thanks
Ramm
-- Test Data
DECLARE #T TABLE(
TextName NVARCHAR(4000)
)
INSERT INTO #T
SELECT 'IF PAIRING IS NOT SUCCESSFUL, REPEAT THE PAIRING PROCESS. IF PAIRING IS STILL NOT SUCCESSFUL, REPLACE THE MOTOR.'
INSERT INTO #T
SELECT 'IF NOT WITHIN THE SPECIFIED RANGE, TEST THE MOTOR FOR A SV, SG, OR AN OHR. IF THE CIRCUIT TESTS NORMAL, REPLACE THE MOTOR.'
-- Example Query
SELECT SUBSTRING(TextName, PosPeriod, PosComma - PosPeriod) 'String1'
FROM
(
SELECT TextName,
CHARINDEX('.', TextName) + 5 'PosPeriod', -- 5 is to skip over the '. IF '
CHARINDEX(',', TextName, CHARINDEX('.', TEXTName)+1 ) 'PosComma'
FROM #T
) TEMPTABLE