Substring instead of Left - sql

All,
I have a query like this:
SELECT
[RecName],
CHARINDEX('_',[Rec Name]),
CASE
WHEN CHARINDEX('_',[Rec Name]) >=1 THEN
LEFT([Rec Name],CHARINDEX('_',[Rec Name])-1)
ELSE
'NA'
END RecTrimmed
FROM calculated_data
WHERE [Rec Name] = 'T101184_7AB_C1_ABCDE'
GROUP BY [Rec Name]
When I execute the above I get the following result - T101184
How can I achieve the same result using Substring?
Any lead would be appreciated.
Thanks,
John

One way is
with cte (col) as
(select 'T101184_7AB_C1_ABCDE' union all
select 'T1011847ABC1ABCDE')
select coalesce(nullif(substring(col,0,charindex('_',col)),''),'NA')
from cte;
Having said that, there is no reason you shouldn't use left for the problem you have at hand

One simple and quick solution could be to use an ordinal splitter to divide the string at '_' into rows. Then there's no need to fiddle around with LEFT and SUBSTRING and CHARINDEX.
The ordinal splitter can be found here
CREATE FUNCTION dbo.DelimitedSplit8K
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
Then the query is very simple and executes efficiently
with cte (col) as (
select 'T101184_7AB_C1_ABCDE' union all
select 'T1011847ABC1ABCDE')
select Item
from cte c
cross apply
(select case when charindex('_',c.col)=0 then 'NA' else c.col end chr) ndx
cross apply
dbo.DelimitedSplit8K(ndx.chr, '_')
where ItemNumber=1;
Output
Item
T101184
NA

Related

Reverse in SQL by pair

I'm very new to SQL and I'd like to do something like this :
Going from
12 34 56 78
to
78 56 34 12
I tried the reverse function, but the result is 87 65 43 21.
Is there a way to do this ? Thank you for reading !
You can use string split to split your string into rows, then string_agg to get a string back with the order you want:
select string_agg(value, ' ') within group(order by cast(value as int) desc)
from string_split('12 34 56 78', ' ')
Fiddle
However if you don't want you numbers in increasing order, you shouldn't use string_split with row_number as suggested in the other answer because the order is NOT guaranteed. Use another function instead of string_split, such as DelimitedSplit8K from here.
Your select becomes:
select string_agg(Item, ' ') within group(order by ItemNumber desc)
from DelimitedSplit8K('12 34 56 78', ' ');
The code of DelimitedSplit8K:
CREATE FUNCTION [dbo].[DelimitedSplit8K]
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Tableā€ produces values from 0 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "zero base" and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT 0 UNION ALL
SELECT TOP (DATALENGTH(ISNULL(#pString,1))) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT t.N+1
FROM cteTally t
WHERE (SUBSTRING(#pString,t.N,1) = #pDelimiter OR t.N = 0)
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY s.N1),
Item = SUBSTRING(#pString,s.N1,ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000))
FROM cteStart s
;
I'm sure the string_split will be useful here. Here's what it can do For your particular case (numbers are always increasing).
select *
from STRING_SPLIT('12 34 56 78', ' ')
order by value desc;
dbfiddle
UPD. Here's what you can do when numbers are not always increasing
with splitted as(
select value, row_number() over(order by (select null)) rn
from string_split('12 34 78 56', ' '))
select string_agg(value, ' ') within group(order by rn desc)
from splitted
dbfiddle

SQL breakup string for use with WHERE IN

I have a table in SQL Server with a column that stores a series of characters. I would like to be able to send a series of characters to a stored procedure and use it for the WHERE IN. Example below
ID | series
---+-------
1 | U
2 | B
3 | R
4 | UB
5 | BR
I would like a return as follows:
Parameter | Return IDs
----------+------------
U | 1
R | 3
U, R | 1, 3
I can format the parameter any way, UR or U, R or whatever. I could break this up in application and call the procedure N times but I would rather not so that I can use an order by in the query.
Here's one way if you can not use a table valued parameter.
declare #table table (ID int, series varchar(16))
insert into #table
values
(1,'U'),
(2,'B'),
(3,'R'),
(4,'UB'),
(5,'BR')
declare #input varchar(4000) = 'U,R'
select
t.*
from #table t
cross apply dbo.DelimitedSplit8K(#input,',') x
where
x.Item = t.series
OR without Cross Apply
;with cte as
(select *
from dbo.DelimitedSplit8K(#input,',') x )
select
t.*
from #table t
inner join cte on Item = t.series
Here is the function which has proven to be a fast method of splitting strings:
CREATE FUNCTION [dbo].[DelimitedSplit8K] (#pString VARCHAR(8000), #pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
/* "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
enough to cover VARCHAR(8000)*/
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO
On way to achieve this is to pass in a delimited string and then create a function to take in your parameter, splits out the values and returns a table value. Then all you need to do is create a stored procedure similar to.
CREATE PROCEDURE MyProc
(
#MyParameter NVARCHAR(3000)
)
AS
SELECT
ID,
Series
FROM
MyTable
WHERE
Series IN (SELECT ID FROM dbo.MyFunctionToSplitDelimitedString(#MyParameter,',')

i have string as 'abc,def,ghi,jkl' [duplicate]

This question already has answers here:
SQL Server split CSV into multiple rows
(4 answers)
Closed 6 years ago.
i want to string in table column in new row as
table
abc
def
ghi
jkl
If you are using SQL SERVER 2016 then use STRING_SPLIT function
SELECT *
FROM String_split('abc,def,ghi,jkl', ',')
If you are using anything less than SQL SREVER 2016 then here is the best split string function. Referred from here
CREATE FUNCTION [dbo].[Delimitedsplit8k] (#pString VARCHAR(8000),
#pDelimiter CHAR(1))
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO
To call the function
SELECT *
FROM dbo.DelimitedSplit8K('abc,def,ghi,jkl', ',')
You can use a Recursive CTE to split the string. It will allow you to track the position of the String within the string (if you want) and also provide a link back to your ID/Key value in your master table. (This allows you to avoid using a function if it's not an option)
CREATE TABLE #S(ID INT
,Qry VARCHAR(10)
)
INSERT INTO #S VALUES
(1,'TRA,B')
,(2,'X,YA,ZT')
DECLARE #s AS VARCHAR(1) = ','
;WITH cte_R
AS
(
SELECT
ID
,1 Ord
,LEFT(Qry,CHARINDEX(#s,Qry,0)) Val
,RIGHT(Qry,LEN(Qry)-CHARINDEX(#s,Qry,1)) Rem
FROM
#S
WHERE
Len(Qry) > 0
UNION ALL
SELECT
ID
,Ord+1
,LEFT(Rem,CHARINDEX(#s,Rem+#s,0))
,RIGHT(Rem,LEN(Rem)-CHARINDEX(#s,Rem,0))
FROM
cte_R
WHERE
CHARINDEX(#s,Val,0) > 0
)
SELECT
ID
,Ord
,REPLACE(Val,#s,'') Val
FROM
cte_R
ORDER BY
ID
,Ord

Getting several lines from a table in SQL Server and list them

I have a list with vehicles likes this:
Let's say I would like to display only cars with the ECUs TMS1 and C200. How do I do that?
I have inserted this function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitString]
(#pString NVARCHAR(4000), #pDelimiter NCHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
WHERE SUBSTRING(#pString, l.N1, l.L1) <> ''
;
GO
and created this stored procedure:
Alter Procedure [db_ddladmin].[spGetVehicles]
(
#ECU nvarchar(20),
#Identifiers nvarchar(20)
)
AS
Begin
SELECT *
FROM db_ddladmin.View_VehicleReadouts
WHERE ECU IN (SELECT Item FROM [dbo].[SplitString](#ECU,',') )
AND Identifier IN (SELECT Item FROM [dbo].[SplitString](#Identifiers, ','))
END
And I execute this stored procedure by this query:
EXEC [db_ddladmin].[spGetVehicles] #ECU = 'EBS7,ALM1', #Identifiers = '88'
I get a list with all the vehicles containing those ECUs and Identifiers. But the thing is that I would only like to display vehicles that has both of the ECUs I have written there and not vehicles that has only one of those desired ECUs. How do I do that?
You can do this with aggregation and having. The idea is to count the number of matches:
with items(item) as (
select Item
from dbo.SplitString(#ECU, ',')
)
select ??
from db_ddladmin.View_VehicleReadouts
where ecu in (select items.item from items)
group by ??
having count(*) = (select count(*) from items);
The ?? represents the column that specifies the vehicle.
If there can be duplicates in the table, then use count(distinct ecu) rather than count(*) in the having clause.

Parsing a column value in SQL

I have a table STG(ID,VALUE,TEXT) with no constraints.
Here is what I have -
ID|VALUE|TEXT
1 |22 |sample
4 |19,17|question
5 |29 |solution
.
.
.
Here is what I want -
ID|VALUE|TEXT
1 |22 |sample
4 |19 |question
4 |17 |question
5 |29 |solution
.
.
.
How can I do this in SQL Server?
You could use for example DelimitedSplit8K function posted in here (quite far in the end):
http://www.sqlservercentral.com/articles/Tally+Table/72993/
And join that with your select with something like this:
select
t.ID,
s.Item,
t.TEXT
from
table t
cross apply dbo.DelimitedSplit8K(t.VALUE, ',') s
Edit, Including the function code:
CREATE FUNCTION [dbo].[DelimitedSplit8K]
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t
WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;