Convert multiple row from one row based on specific character - sql

I am trying to convert from one row to multiple row based on specific character
I copied a script from someone which was working with his/her example but not working for me which is as below
;WITH tmp(NOTEINDX, DataItem, TXTFIELD) AS
(
SELECT
NOTEINDX,
LEFT(TXTFIELD, CHARINDEX('#', TXTFIELD + '#') - 1),
STUFF(TXTFIELD, 1, CHARINDEX('#', TXTFIELD + '#'), '')
FROM SY03900
UNION all
SELECT
NOTEINDX,
LEFT(TXTFIELD, CHARINDEX('#', TXTFIELD + '#') - 1),
STUFF(TXTFIELD, 1, CHARINDEX(',', TXTFIELD + '#'), '')
FROM tmp
WHERE
TXTFIELD > ''
)
SELECT
NOTEINDX,
DataItem
FROM tmp
ORDER BY NOTEINDX
However I am getting below error
Msg 402, Level 16, State 1, Line 6
The data types text and varchar are incompatible in the add operator.
I'm using SQL Server 2008
Thanks,
Hatim

Related

how can I get the specified content by the string

QUESTION DESCRIPTION:
My oracle query SQL result have a column, the column value is a string description like as follow.
How can I get the special substring that I want, such as I only want the pilot's name.
{"flightRiskValue":{"airportDifficulty":0.00,"airportExp":0.00,"airportExp_captain":0.00,"airportTechNos":0.20,"airportTechNos_captain":0.40,"flightCrewNum":0.00,"flightExp":0.00,"flightExp_captain":0.00,"groupExp":0.70,"ilsWorkStatus":0.00,"pilotCrewLimit":0.00,"pilotCrewLimit_captain":0.00,"pilotDutyLevel":0.05,"pilotDutyLevel_captain":0.05,"pilotFindAnyFemale":0.00,"pilotScheduleTechLevel":0.00,"pilotScheduleTechLevel_captain":0.00,"pilotWorkTimeMonth":0.00,"pilotWorkTimeMonth_captain":0.00,"pilotWorkTimeWeek":0.15,"pilotWorkTimeWeek_captain":0.10,"pilotsIsDeptTeam":0.00,"rain":0.00,"rainAndSnow":0.00,"seeing":0.00,"snow":0.00,"wind":0.00},"pilotDTOList":["副驾驶:5-2|杜佳佳|F3;","副驾驶:5-1|凯尔|F4;","第二机长/巡航机长:5-1|贺云|A1;","机长:5-2|张磊3|A1;"],"riskValue":1.95,"version":"1"}
EXPECTED:
How can I get the special substring such as follow I want substring:
|杜佳佳|,|凯尔|,|贺云|,|张三|
and I want a column become more columns according to this column
first pilot name
second pilot name
....
杜佳佳
凯尔
贺云...
You can extract each of the items in the JSON array directly into different columns (eliminating the need to PIVOT) and then find the substrings (without needing to use [slow] regular expressions):
SELECT SUBSTR(
pilot1,
INSTR(pilot1, '|', 1, 1) + 1,
INSTR(pilot1, '|', 1, 2) - INSTR(pilot1, '|', 1, 1) - 1
) AS first_pilot_name,
SUBSTR(
pilot2,
INSTR(pilot2, '|', 1, 1) + 1,
INSTR(pilot2, '|', 1, 2) - INSTR(pilot2, '|', 1, 1) - 1
) AS second_pilot_name,
SUBSTR(
pilot3,
INSTR(pilot3, '|', 1, 1) + 1,
INSTR(pilot3, '|', 1, 2) - INSTR(pilot3, '|', 1, 1) - 1
) AS third_pilot_name,
SUBSTR(
pilot4,
INSTR(pilot4, '|', 1, 1) + 1,
INSTR(pilot4, '|', 1, 2) - INSTR(pilot4, '|', 1, 1) - 1
) AS fourth_pilot_name
FROM table_name t
CROSS APPLY JSON_TABLE(
t.value,
'$'
COLUMNS (
pilot1 NVARCHAR2(200) PATH '$.pilotDTOList[0]',
pilot2 NVARCHAR2(200) PATH '$.pilotDTOList[1]',
pilot3 NVARCHAR2(200) PATH '$.pilotDTOList[2]',
pilot4 NVARCHAR2(200) PATH '$.pilotDTOList[3]'
)
) j
Which, for the sample data, outputs:
FIRST_PILOT_NAME
SECOND_PILOT_NAME
THIRD_PILOT_NAME
FOURTH_PILOT_NAME
杜佳佳
凯尔
贺云
张磊3
db<>fiddlle here

How to set substring statement as valid column name in SQL Server

I have a code like the following:
INSERT INTO [TranslateValidate]..[Policy] ([BirthDate],[FirstName],[LastName])
SELECT
[Table2309].[DOB],
SUBSTRING(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name)),
SUBSTRING(Full_Name, 0, CHARINDEX(',', Full_Name))
FROM [Table2309] AS [Table2309]
WHERE [Table2309].[clientid] = (SELECT
MIN(clientid)
FROM Table2309 T
WHERE T.Date_of_Birth = Table2309.Date_of_Birth
AND T.Substring(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name)) = Table2309.Substring(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name))
AND T.Substring(Full_Name, 0, CHARINDEX(',', Full_Name)) = Table2309.Substring(Full_Name, 0, CHARINDEX(',', Full_Name))
This would have an error message
Cannot find either column "c" or the user-defined function or aggregate "c.Substring", or the name is ambiguous.
If I add [] for Substring part, this would should error message
Invalid column name 'Substring(Full_Name,...
How do I resolve this problem?
You have an extra comma at the end of your select statement:
SELECT
[Table2309].[DOB],
SUBSTRING(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name)),
SUBSTRING(Full_Name, 0, CHARINDEX(',', Full_Name))**,**
Remove this comma and it should work fine.

SQL Server - Extract text from a given string field

What is the best method to extract the text from the string field below?
I am trying to extract the ProjectID numbers (91, 108, 250) below but am struggling because the ProjectIDs are either 2 or 3 integers long and are within different parts of the string.
Row Parameter
1 ProjectID=91&GroupID=250&ParentID=1
2 ProjectID=108&GroupID=250&ParentID=35
3 GroupID=1080&ProjectID=250&ParentID=43
4 ProjectID=250
Any help would be much appreciated.
SQL Server is kind of lousy on string functionality. Here is one method:
select left(v1.p, patindex('%[^0-9]%', v1.p + ' ') - 1)
from (values ('ProjectID=91&GroupID=250&ParentID=1'),
('ProjectID=108&GroupID=250&ParentID=35'),
('GroupID=1080&ProjectID=250&ParentID=43'),
('ProjectID=250')
) v(parameter) cross apply
(values (stuff(v.parameter, 1, charindex('ProjectID=', v.parameter) + 9, ''))
) v1(p);
Or split the string and look for a match:
select stuff(s.value, 1, 10, '')
from (values ('ProjectID=91&GroupID=250&ParentID=1'),
('ProjectID=108&GroupID=250&ParentID=35'),
('GroupID=1080&ProjectID=250&ParentID=43'),
('ProjectID=250')
) t(parameter) cross apply
string_split(t.parameter, '&') s
where s.value like 'ProjectId=%';
Here is a db<>fiddle.
SELECT
substring ( #Parameter,
CHARINDEX('ProjectID', #Parameter) + 10,
CHARINDEX('&', #parameter, CHARINDEX('ProjectID', #Parameter)) -
(CHARINDEX('ProjectID', #Parameter) + 10))
from table

Msg 240, Types don't match between the anchor and the recursive part in column

I am trying to split a row when the ';' character appears. I have a list with projects, where one of the columns states which district the project belongs to. However some projects appears in multiple districts and is therefore written like "1;2;3" (District 1, 2 and 3). I want to create three rows form this and split on the ';'.
The error message says:
Msg 240, Level 16, State 1, Line 13
Types don't match between the anchor and the recursive part in column "DataItem" of recursive query "tmp".
I tried the split_string, but discovered my server is 2014 and lacks compatibility.
WITH tmp(Oppdragsnr, Kommune, DataItem, Kommunenr) AS
(
SELECT
Oppdragsnr,
Kommune,
LEFT(Kommunenr, CHARINDEX(';', Kommunenr + ';') - 1),
STUFF(Kommunenr, 1, CHARINDEX(';', Kommunenr + ';'), '')
FROM
oppdragene
UNION all
SELECT
Oppdragsnr,
Kommune,
LEFT(Kommunenr, CHARINDEX(';', Kommunenr + ';') - 1),
STUFF(Kommunenr, 1, CHARINDEX(';', Kommunenr + ';'), '')
FROM
tmp
WHERE
Kommunenr > ''
)
SELECT
Oppdragsnr,
Kommune,
DataItem
FROM
tmp
ORDER BY
Oppdragsnr
I would like the output to be a new table with new rows for every project that appears in multiple districts.
You should probably CAST to INT the DataItem column in the base and recursive part of the query, the following query should work for you
;WITH tmp(Oppdragsnr, Kommune, DataItem, Kommunenr) AS
(
SELECT
Oppdragsnr,
Kommune,
CAST(LEFT(Kommunenr, CHARINDEX(';', Kommunenr + ';') - 1) AS INT),
STUFF(Kommunenr, 1, CHARINDEX(';', Kommunenr + ';'), '')
FROM
oppdragene
UNION all
SELECT
Oppdragsnr,
Kommune,
CAST(LEFT(Kommunenr, CHARINDEX(';', Kommunenr + ';') - 1) AS INT),
STUFF(Kommunenr, 1, CHARINDEX(';', Kommunenr + ';'), '')
FROM
tmp
WHERE
Kommunenr > ''
)
SELECT
Oppdragsnr,
Kommune,
DataItem
FROM
tmp
ORDER BY
Oppdragsnr

Invalid length parameter passed to the LEFT or SUBSTRING function in Sql Server

While trying to execute the below query
Declare #t table (id int, string varchar(1000))
INSERT INTO #t (id, string)
SELECT 1, 'zxzzxx,ppppbppp,trtrtr,tyyt,hgghh,fefew,rewr,rwerer'
;WITH test (id, lft, rght, idx)
AS
(
SELECT t.id
,LEFT(t.string, CHARINDEX(', ', t.string) - 1)
,SUBSTRING(t.string, CHARINDEX(', ', t.string) + 2, DATALENGTH(t.string))
,0
FROM #t t
UNION ALL
SELECT c.id
,CASE WHEN CHARINDEX(', ', c.rght) = 0 THEN c.rght ELSE LEFT(c.rght, CHARINDEX(', ', c.rght) - 1) END
,CASE WHEN CHARINDEX(', ', c.rght) > 0 THEN SUBSTRING(c.rght, CHARINDEX(', ', c.rght) + 2, DATALENGTH(c.rght))
ELSE '' END
,idx + 1
FROM test c
WHERE DATALENGTH(c.rght) > 0
)
select id, lft from test
I am getting the below error
Msg 537, Level 16, State 2, Line 8
Invalid length parameter passed to the LEFT or SUBSTRING function.
but the same works for SELECT 1, 'the, quick, brown, fox, jumped, over, the, lazy, dog'
Please help
It seems to be a space missing between your words.
You are currently looking for charindex of ', ' not ','.
And the string does not have any match of ', '.
This Error message happens usually when you do these steps;
When you use Substring,
left, right functions.
When you use CharIndex (used in
the field, the selected word or word
search, or the length of a character
to be inadequate)
The return value is returned to each server in the query expression, the result of the transaction 0 (zero) returns, if error returns -1
This will not result in errors for the server to return a value of -1 or are compared objects.