How to split string in multiple column in sql server [duplicate] - sql

This question already has answers here:
How to split a comma-separated value to columns
(38 answers)
Closed 7 years ago.
I have string "1:182:1,1:195:2,1:213:1".
I spllited the string with ',' in different rows. Now I want each rows single column to be splitted in 3 different columns in same row.
I tried using
SELECT LEFT(ThemeProperty, CHARINDEX(':', ThemeProperty) - 1) ,
RIGHT(ThemeProperty,
LEN(ThemeProperty) - CHARINDEX(':', ThemeProperty))
FROM #tempThemeProperty
But its output is
(No column name) (No column name)
1 182:1
1 195:2
1 213:1
But I want it to be
Column1 Column2 Column3
1 182 1
So any help would be appreciated.

DECLARE #Tmp TABLE (Id INT,Name VARCHAR(20))
INSERT #Tmp SELECT 1,'182:1'
INSERT #Tmp SELECT 2,'195:2'
INSERT #Tmp SELECT 3,'213:1'
--Using PARSENAME
SELECT Id,
PARSENAME(REPLACE(Name,':','.'),2) Value1,
PARSENAME(REPLACE(Name,':','.'),1) Value2
FROM #Tmp
This should be able to di it.. Let me know if it helps

This is one method but subject to sql injection
declare #s varchar(2000),#data varchar(2000)
select #s='1:182:1'
select #data=''''+replace(#s,':',''',''')+''''
exec('select '+#data)

Related

Find the frequency of all words from a concatenated column

I have concatenated text column derived from three columns in a table. I need to have frequency of all single words from that concatenated column.
Column1 Column2 column3
This is Test 1
This was Test two
What I need is concatenation of all three i.e. This is Test 1, This was Test two and then count of each word ie.
This - 2
is - 1
was -1
Test - 2
1- 1
two - 1
You can use string_split and cross apply to achieve the required result. try the following:
Code:
declare #tab table (col1 varchar(100), col2 varchar(100), col3 varchar(100))
insert into #tab
select 'This is', 'Test', '1'
union
select 'This was','Test','two'
select value, count(*) rec_count
from #tab
cross apply string_split((col1+' '+col2+' '+col3), ' ')
group by value

Not able to separate delimited data in sqlserver [duplicate]

This question already has answers here:
T-SQL split string
(27 answers)
Closed 3 years ago.
I have column named Description, in that the rows are inserted along with a delimiter '-'.
I used the query to separate it. The query is mentioned below
select Description from Sheet1$
cross apply
SplitString('Description','-')
The columns have following data
Description
00000131-125
0000154-4625-4569-4568-45213
Try this below
DECLARE #Str AS TABLE ([Description] varchar(max) )
INSERT INTO #Str
SELECT '00000131-125' UNION ALL
SELECT '0000154-4625-4569-4568-45213'
SELECT Id,
LTRIM(RTRIM(Split.a.value('.','nvarchar(100)'))) AS [Description]
FROM
(
SELECT
ROW_NUMBER()OVER(ORDER BY (SELECT Null)) AS Id,
CAST('<S>'+(REPLACE([Description],'-','</S><S>')+'</S>') AS XML ) AS [Description]
FROM #Str
)AS A
CROSS APPLY [Description].nodes('S') AS Split(a)
Adding FOR XML PATH to the end of a query allows you to output the results of the query as XML elements, with the element name contained in the PATH argument.
Result
Id Description
---------------
1 00000131
1 125
2 0000154
2 4625
2 4569
2 4568
2 45213

Parse two Numbers from Text

I want to parse number from Text Line in SQL.
My Text line is as:
I want to retrieve values of First & second as column using SQL as below.
Here's an implementation that you can then use as a procedure on select:
DECLARE #row VARCHAR(MAX);
SET #row = 'First:87.85 Second:87.88 mtr'
DECLARE #result VARCHAR(MAX);
SET #result =
RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(#row,'mtr',''),'First:',''),'Second:','')))
SELECT
SUBSTRING(#result,0,charindex(' ',#result)) As First,
SUBSTRING(#result,charindex(' ',#result),LEN(#result)) AS Second
This treats one row at a time.
Live demo
Assuming the structure of the strings is fixed, one fairly simple way is to use a common table expression with lots of charindex columns to get the start and end positions of the numbers, and then select from that cte with substring.
First, create and populate sample table(Please save us this step in your future questions)
DECLARE #T AS TABLE
(
col varchar(100)
)
INSERT INTO #T (col) VALUES
('First:87.85 Second:87.85 mtr'),
('First:8 Second:82 mtr'),
('First:85 Second:8 mtr'),
('First:7.5 Second:87 mtr');
The cte:
WITH CTE AS
(
SELECT col As String,
7 As FirstStart,
CHARINDEX(' Second', col) As FirstEnd,
CHARINDEX(' Second', col) + 8 As SecondStart,
CHARINDEX(' ', col, CHARINDEX(' Second', col)+1) As SecondEnd
FROM #T
)
The select statement:
SELECT SUBSTRING(String, FirstStart, FirstEnd - FirstStart) As First,
SUBSTRING(String, SecondStart, SecondEnd - SecondStart) As Second
FROM CTE
Results:
First Second
87.85 87.85
8 82
85 8
7.5 87
You can see a live demo on rextester.

SQL Server 2014 - How to split a string with commas into multiple rows? [duplicate]

This question already has answers here:
Turning a Comma Separated string into individual rows
(16 answers)
Closed 6 years ago.
I have written a query which returns a table (tb1) with rows of data. One column shows a list of queues an analyst can work on and the other columns show how many analysts are available to work on those queues and how many are away.
I now need to wrap this query in another so it returns the row, broken down into multiple rows each showing how many analysts are avail/away per queue.
table 1
UPDATE - I have created this post when there are similar ones out there because the Queue column is the key, which needs to be separated into individual rows each with the same data from the other (avail/away) columns when it was just one row. To add complexity there can be some rows with more/less queue names that need grouping. example is updated.
Here is my udf. There are many variations out there. What I like about this one is you get the sequence number
EDIT:
Sorry, I didn't see your image. But with the help of a Cross Apply
Declare #YourTable table (id int,SomeField varchar(50))
Insert into #YourTable values
(1,'Smith,John'),
(2,'Doe,Jane')
Select A.ID
,YourNewFieldName=B.Key_Value
From #YourTable A
Cross Apply (Select * from [dbo].[udf-Str-Parse](A.SomeField,',')) B
Returns
ID YourNewFieldName
1 Smith
1 John
2 Doe
2 Jane
The UDF
CREATE FUNCTION [dbo].[udf-Str-Parse] (#String varchar(max),#Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
-- Select * from [dbo].[udf-Str-Parse]('id26,id46|id658,id967','|')
-- Select * from [dbo].[udf-Str-Parse]('hello world. It. is. . raining.today','.')
Returns #ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
Declare #XML xml;Set #XML = Cast('<x>' + Replace(#String,#Delimeter,'</x><x>')+'</x>' as XML)
Insert Into #ReturnTable Select Key_Value = ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM #XML.nodes('x') as T(String)
Return
End
Sample Return
Key_PS Key_Value
1 Dog
2 Cat
3 House
4 Car

SQL - Select Uppercase fields

i have a table, that has a column (SQL_Latin1_General_CP1_CI_AI), and has a couple of hundred rows where that column is filled in all uppercase.
I would like to know if it is possible to select all the rows that have that field in uppercase and, ultimately if i can make an update to capitalize the fields.
I'm using SQL Management Studio on MSSQL 2005
Thanks
DECLARE #T TABLE
(
col VARCHAR(3) COLLATE SQL_Latin1_General_CP1_CI_AI
)
INSERT INTO #T
SELECT 'foo' UNION ALL SELECT 'BAR' UNION ALL SELECT ''
UPDATE #T
SET col = STUFF(LOWER(col),1,1,LEFT(col,1))
WHERE col = UPPER(col) COLLATE SQL_Latin1_General_CP1_CS_AS AND LEN(col) >1
SELECT * FROM #T
Returns
(1 row(s) affected)
col
----
foo
Bar
(3 row(s) affected)