Split and get second row as value [duplicate] - sql-server

This question already has answers here:
Using T-SQL, return nth delimited element from a string
(14 answers)
Closed 4 years ago.
I'm using below query to split the names as shown below:
select value from STRING_SPLIT('Name1~Name2~Name3' , '~' );
How to get second name i.e, Name2, without using WHERE condition?
Note: Names can be dynamic

Try PARSENAME function
SELECT PARSENAME( REPLACE('Name1~Name2~Name3','~','.'),2)
output
Name2
PARSENAME Returns the specified part of an object name. The parts of an object that can be retrieved are the object name, owner name,
database name, and server name.

Instead of using STRING_SPLIT you can convert your string to XML and then use .value to retrieve the 2nd element:
SELECT CAST('<t>' + REPLACE('Name1~Name2~Name3' , '~','</t><t>') + '</t>' AS XML).value('/t[2]','varchar(50)')

Try below code:
SELECT TOP 1 T.* FROM
(SELECT TOP 2 * FROM STRING_SPLIT('Name1~Name2~Name3' , '~' ) ORDER BY value ASC) AS T
ORDER BY value DESC;

Related

Using coalesce to concatenate a variable character and lenght filled field [duplicate]

This question already has answers here:
nvarchar concatenation / index / nvarchar(max) inexplicable behavior
(2 answers)
VARCHAR(MAX) acting weird when concatenating string
(1 answer)
Closed last year.
I have a query that selects values from two joined tables, one table has the value to join and another table has the "format" configuration.
SELECT #SegmentValue = COALESCE ( #SegmentValue +
CASE
WHEN el.FillFormat = 'RIGHT'
THEN LEFT ( val.CalculatedValue + REPLICATE(el.fillcharacter, el.Length) , el.Length)
ELSE LEFT ( val.CalculatedValue + REPLICATE(el.fillcharacter, el.Length) , el.Length)
END
,''
)
FROM EDI_Element el
INNER JOIN #EDI_Element_Values val ON
This query is having a very interesting behavior; as it is the variable that only has the very last value, so if I return 4 records like r1 , r2 r3 , r4 (I tested this by running the exact same query but with select * instead of the coalesce as I first suspected the joins) the variable will have a value of r4.
An interesting thing I found is that if I hardcode a value inside the replicate for example 100, the query works as expected.

How would you use string functions to separate data by individual terms [duplicate]

This question already has answers here:
How do I split a delimited string so I can access individual items?
(46 answers)
Splitting a Full Name into First and Last Name
(7 answers)
Closed 3 years ago.
I am trying to split names into columns, for example, column 1 named "Name would contain in row 1 the varChar "Jesus Lopez" How could I split it up so that I can create a second column with row 1 to contain "Jesus" and a third column with row 1 to contain "Lopez". I can only use string functions to accomplish this task.
I thought about using the Left() function and Nest Charindex() to find the first set of string. I'm trying to figure out gather the rest of the name and put it on its own column.
Select Name,
Left(Name, Charindex(' ', Name)) as FirstName,
From Person.StateProvince
I expect to have a total of 3 columns. One with the original name, another with the first name only, and lastly a third column with what ever is left from the data in the first column.
What is the requirement with the spaces? Considering you want to ignore any leading or trailing spaces for the values, and making the value as NULL when the value is not there, this would work:
SELECT Name
,FirstName = CASE WHEN CHARINDEX(' ', LTRIM(Name)) > 1 THEN LEFT(LTRIM(Name), CHARINDEX(' ', LTRIM(Name))-1) WHEN LEN(LTRIM(RTRIM(Name))) > 1 THEN LTRIM(RTRIM(Name)) ELSE NULL END
,Remaining = CASE WHEN CHARINDEX(' ', LTRIM(RTRIM(Name))) > 0 THEN LTRIM(SUBSTRING(LTRIM(Name),CHARINDEX(' ', LTRIM(Name))+1, LEN(LTRIM(Name)) - CHARINDEX(' ', LTRIM(Name)))) ELSE NULL END
FROM Person.StateProvince;
If you're string has not more than four parts then you could use PARSENAME
SELECT [Name]
,PARSENAME(REPLACE([Name],' ','.'),4) AS Part1
,PARSENAME(REPLACE([Name],' ','.'),3) AS Part2
,PARSENAME(REPLACE([Name],' ','.'),2) AS Part3
,PARSENAME(REPLACE([Name],' ','.'),1) AS Part4
FROM #temp

bring column name into row in sql server [duplicate]

This question already has answers here:
Unpivot with column name
(3 answers)
Closed 4 years ago.
I have a table with column column_name_1 , column_name_2 , column_name_3 and with one row values 0,0,1
column_name_1 , column_name_2 , column_name_3
--------------,----------------,---------------
0 , 0 , 1
I need output like
column_name_1 | 0
column_name_2 | 0
column_name_3 | 1
Is it possible?
I have checked for some unpivot example, thats not exactly my case.
Because I need Column name into column value and one row into column.
1.Unpivot with column name
Name, Maths, Science, English
Tilak, 90, 40, 60
Raj, 30, 20, 10
changed into
Name, Subject, Marks
Tilak, Maths, 90
Tilak, Science, 40
Tilak, English, 60
Clearly there is a view, Name column remains its position as it is.
2.SQL Query for generating matrix like output querying related table in SQL Server
Above link also have Customer Name column which is remains same as it is.
But in my case input and output, both not have any same position.
So if still it can be achievable through pivot, Pls help with the code.
Clearly UNPIVOT would be more performant, but if you need a dynamic approach without actually using dynamic SQL
Example
Select C.*
From YourTable A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
Select Item = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From B.XMLData.nodes('/row') as C1(n)
Cross Apply C1.n.nodes('./#*') as C2(a)
Where a.value('local-name(.)','varchar(100)') not in ('Columns','ToExclude')
) C
Returns
Item Value
Column_name_1 0
column_name_2 0
column_name_3 1
You want APPLY :
SELECT tt.cols, tt.colsvalue
FROM table t CROSS APPLY
( VALUES ([column_name_1], 'column_name_1'),
([column_name_2], 'column_name_2'),
([column_name_3], 'column_name_3')
) tt (colsvalue, cols);

T SQL - splitting column into two columns after first '-' [duplicate]

This question already has answers here:
T-SQL split string based on delimiter
(9 answers)
Closed 6 years ago.
Got dbo where i need to split it into two, after first '-' character. Working on SSMS 2014
example in spreadsheet:
example
PartNumber holds data which needs to be break up.
Part - Need to have all characters before first '-'
Number - need to have all characters after first '-'
Any help appreciated
thanks
You need LEFT and RIGHT. And to find the location where you want to split to LEFT and RIGHT, us CHARINDEX.
Maybe something like this?
SELECT parts.PartID as ID,
Part = (SELECT TOP 1 value FROM STRING_SPLIT(parts.PartNumber, '-')),
Number = (SELECT value FROM STRING_SPLIT(parts.PartNumber, '-') LIMIT 1 OFFSET 1),
FROM dbo.PartsTable parts
You could try this.
SELECT
PartNum
, REPLACE(LEFT(PartNum, CHARINDEX('-', PartNum)),'-', '') as 'PartNum First'
, REPLACE(SUBSTRING(PartNum,CHARINDEX('-', PartNum), LEN(PartNum)), '-','') as 'PartNum Second'
FROM Part
The query above splits the PartNum string when it finds '-', it then replaces it with a blank space so you have the result you expected.
I tried it and it works. Hope it's useful to you.
Declare #YourTable table (PartNumber varchar(50))
Insert Into #YourTable values
('HHY-12-1800-2'),
('FC-P-41-4')
Select PartNumber
,Part = Left(PartNumber,CharIndex('-',PartNumber)-1)
,Number = Substring(PartNumber,CharIndex('-',PartNumber)+1,Len(PartNumber))
From #YourTable
Returns
PartNumber Part Number
HHY-12-1800-2 HHY 12-1800-2
FC-P-41-4 FC P-41-4

Concatenating Column Values into a Comma-Separated string [duplicate]

This question already has answers here:
How to use GROUP BY to concatenate strings in SQL Server?
(22 answers)
Closed 7 years ago.
I have a table which looks like the following:
EventProfileID ParamName ParamValue
1 _CommandText usp_storedproc_1
2 _CommandText usp_storedproc_2
2 _CommandText usp_storedproc_3
2 _CommandText usp_storedproc_100
3 _CommandText usp_storedproc_11
3 _CommandText usp_storedproc_123
What I would like my output to be is the following:
EventProfileID ParamValue
1 usp_storedproc_1
2 usp_storedproc_2, usp_storedproc_3, usp_storedproc_100
3 usp_storedproc_11, usp_storedproc_123
However I am having some bother. If I do a select on one of the event profile ID's I can get an output using the following logic:
SELECT LEFT(c.ParamValue, LEN(c.ParamValue) - 1)
FROM (
SELECT a.ParamValue + ', '
FROM DP_EventProfileParams AS a
WHERE a.ParamName = '_CommandText'
and a.EventProfileId = '13311'
FOR XML PATH ('')
) c (paramvalue)
However that just gives me the output for one EventProfileID and also I would like the EventProfileID as part of the output.
Can anyone give me any pointers in the right direction into how I can expand my code to include this and allow the code to be dynamic so that I can show all EventProfileID's?
Thanks
You can do it this way:
select distinct a.EventProfileID,
stuff((select ','+ ParamValue)
from DP_EventProfileParams s
where s.EventProfileID = a.EventProfileID
for XML path('')),1,1,'')
from DP_EventProfileParams a
You were on the right track with for XML path. STUFF function makes it easier to achieve what you want.
The original query does not work because it uses simple subquery (works only for one specific id)
To make it work for all ids you can use XML + STUFF inside correlated subquery:
Many queries can be evaluated by executing the subquery once and
substituting the resulting value or values into the WHERE clause of
the outer query. In queries that include a correlated subquery (also
known as a repeating subquery), the subquery depends on the outer
query for its values. This means that the subquery is executed
repeatedly, once for each row that might be selected by the outer
query.
SELECT DISTINCT
EventProfileID,
[ParamVaues] =
STUFF((SELECT ',' + d2.ParamValue
FROM #DP_EventProfileParams d2
WHERE d1.EventProfileID = d2.EventProfileID
AND d2.ParamName = '_CommandText'
FOR XML PATH('')), 1, 1, '')
FROM #DP_EventProfileParams d1
ORDER BY EventProfileID;
LiveDemo
I strongly suggest reading Concatenating Row Values in Transact-SQL

Resources