I want to select a list of items and part numbers for for each item as a string:
SELECT top 100 *
FROM ii
OUTER APPLY
(SELECT def, ( ipr.part_number + ',') as prt
FROM ipr
WHERE ii.item_id = ipr.item_id
FOR XML PATH('') ) PN
The error is:
[Error Code: 8155, SQL State: S0002] No column name was specified for
column 1 of 'PN'.
How can I fix this?
I think that your whole OUTER APPLY statement generates one XML for both default_part_number and concatenated string, which(the whole XML) doesn't have a name.
What you could try to do would be adding alias like this AS PN(TestThis).
However, I don't think that you're expecting result you're going to get. It would better if you'd give us some example data and expected output. It will be easier for us to solve your problem in that case.
The combination of XML and STUFF is funny but perfectly fitting to your needs.
First you concat your strings with the ', ' in front, then you must return your XML with ", TPYE). You must read the result with ".value()" and use STUFF to replace the first ', '.
You'll find a lot of exampels in the net...
Related
I am trying to find a way to preserve a space within SQL concatenation.
For context: A table I am selecting from a table with a single concatenated key column. Concatenated keys respect spaces.
Example: BUKRS(4) = 'XYZ ', WERKS(4) = 'ABCD' is represented as key XYZ ABCD.
I am trying to form the same value in SQL, but it seems like ABAP SQL auto-trims all trailing spaces.
Select concat( rpad( tvko~bukrs, 4, (' ') ), t001w~werks ) as key, datab, datbi
from t001w
inner join tvko on tvko~vkorg = t001w~vkorg
left join ztab on ztab~key = concat( rpad( tvko~bukrs, 4, (' ') ), t001w~werks ) "This is why I need the concat
rpad( tvko~bukrs, 4, ' ' ) in this example returns XYZ, instead of XYZ , which leads to concatenated value being XYZABCD, rather than XYZ ABCD.
lpad seems to work just fine (returning XYZ), which leads me to believe I'm doing something wrong.
SQL functions don't accept string literals or variables (which preserve spaces in the same circumstances in ABAP) as they are non-elementary types.
Is there any way to pad/preserve the spaces in ABAP SQL (without pulling data and doing it in application server)?
Update: I solved my problem by splitting key selection from data selection and building the key in ABAP AS. It's a workaround that avoids the problem instead of solving it, so I'll keep the question open in case an actual solution appears.
EDIT: this post doesn't answer the question of inserting a number of characters which vary based on values in some table columns e.g. LENGTH function is forbidden in RPAD( tvko~bukrs, LENGTH( ... ), (' ') ). It's only starting from ABAP 7.55 that you can indicate SQL expressions instead of fixed numbers. You can't do it in ABAP before that. Possible workarounds are to mix ABAP SQL and ABAP (e.g. LIKE 'part1%part2' and then filtering out using ABAP) or to use native SQL directly (ADBC, AMDP, etc.)
Concerning how the trailing spaces are managed in OpenSQL/ABAP SQL, they seem to be ignored, the same way as they are ignored with ABAP fixed-length character variables.
Demonstration: I simplified your example to extract the line Walldorf plant:
These ones don't work (no line returned):
SELECT * FROM t001w
WHERE concat( 'Walldorf ' , 'plant' ) = t001w~name1
INTO TABLE #DATA(itab_1).
SELECT * FROM t001w
WHERE concat( rpad( 'Walldorf', 1, ' ' ), 'plant' ) = t001w~name1
INTO TABLE #DATA(itab_2).
These 2 ones work, one with leading space(s), one using concat_with_space:
SELECT * FROM t001w
WHERE concat( 'Walldorf', ' plant' ) = t001w~name1
INTO TABLE #DATA(itab_3).
SELECT * FROM t001w
WHERE concat_with_space( 'Walldorf', 'plant', 1 ) = t001w~name1
INTO TABLE #DATA(itab_4).
General information: ABAP documentation - SQL string functions
EDIT: working example added, using leading space(s).
I have following existing code in one of the stored procedures to all delimiter / between error messages encounters in the validations:
;with delimiting_errors
(Id,
Delimited_Error_List)
as
(
select
e2.Id,
'/'
+ (select ' ' + Fn
from Customer e
where e.Id = e2.Id
for xml path(''), type
).value('substring(text()[1],2)', 'varchar(max)') as Delimited_Error
from Customer e2
group by e2.Id
)
SELECT * FROM delimiting_errors
Request you to please help me in understanding the command
value('substring(text()[1], 2)', 'varchar(max)')
I tried to search about text(), but couldn't find exact documentation for the same.
Similarly, how substring function is working only on 2 parameters in substring(text()[1], 2), which actually requires 3 parameter.
Please help me with the concept behind this command, also please help me with some resource to read about Text().
What is going on here:
.value('substring(text()[1],2)', 'varchar(max)')
value() function to extract a specific value from the XML, and convert it to a SQL Server data type, in your case to varchar(max)
substring is XQuery substring, not SQL substring, here it returns substring starting at position 2
text() function here retrieves the inner text from within the XML
[1] suffix acts as an indexer, and fetches the first result matched
For more info read XQuery Language Reference, it's like "another language" inside SQL.
.value('substring(text()[1],2)', 'varchar(max)') as Delimited_Error
You use this XML-trick to concatenate values. In the beginning you add a double space select ' ' + Fn, this must be taken away for the beginning of the return string.
So, the .value returns the "substring" (XPath-Function!) of the inner text() starting at the index 2.
Find more information here: http://wiki.selfhtml.org/wiki/XML/XSL/XPath/Funktionen
My stored procedure receives a parameter which is a comma-separated string:
DECLARE #review_status varchar(200)
SET #review_status='CANCELLED,INSPECTED,REJECTED,UNASSIGNED'
I use this variable with LIKE Operator, when value without comma then perfect but it comes with comma then unable to handle.
Now i use this statement
SELECT * FROM tblReview WHERE
review_status LIKE '%' + #review_status + '%'
I need to make from it this statement
SELECT * FROM tblReview WHERE
review_status LIKE '%CANCELLED%' OR --Pass #review_status
review_status LIKE '%INSPECTED%' OR
review_status LIKE '%REJECTED%'.....
What is the best practice for doing this?
You could use a string splitter to do this. Read this article for one of the fastest splitter there is.
Then you need to use the IN operator to do the filtering:
SELECT *
FROM tblReview
WHERE review_status IN(
SELECT item FROM dbo.DelimitedSplit8K(#review_status,',')
)
Since you're using LIKE, you may want to do JOIN instead of IN:
SELECT *
FROM tblReview t
INNER JOIN dbo.DelimitedSplit8K(#review_status, ',') s
ON t.review_status LIKE '%' + s.Item + '%'
Try to first convert varchar with commas to a table as described here http://blogs.msdn.com/b/amitjet/archive/2009/12/11/sql-server-comma-separated-string-to-table.aspx. Then, use the following:
CREATE TABLE #allPattern (
pattern NVARCHAR(max)
);
INSERT INTO #allPattern VALUES ('%CANCELLED%'), ('%INSPECTED%'), ('%REJECTED%');
SELECT t.* FROM tblReview t JOIN #allPattern a ON (t.review_status LIKE a.pattern);
You can add the pre- and trailing comma to yous string, and then use CHARINDEX().
SET #review_status=',CANCELLED,INSPECTED,REJECTED,UNASSIGNED,'
SELECT * FROM tblReview WHERE
charindex(','+review_status+',', '#review_status') >0
Commas at the beginning and at the end of the string are used to make an exact string finding possible - for example, if you have two statuses - one called CAN and the second called CANCELLED, charindex without side commas will find them both.
It's the simplest way, but not the one with the best performance, so don't use it on long CSVs.
I have string data in the following format:
MODELNUMBER=Z12345&HELLOWORLD=WY554&GADTYPE=PLA&ID=Z-12345
/DTYPE=PLA&ID=S-10758&UN_JTT_REDIRECT=UN_JTT_IOSV
and need to extract IDs based on two conditions
Starting after a pattern &ID=
Ending till the last character or
if it hits a & stop right there.
So in the above example I'm using the following code:
SUBSTRING(MyCol,(PATINDEX('%&id=%',[MyCol])+4),(LEN(MyCol) - PATINDEX('%&id%',[MyCol])))
Essentially looking the pattern &id=% and extract string after that till end of the line. Would anyone advise on how to handle the later part of the logic ..
My current results are
Z-12345
Z-12345&UN_JTT_REDIRECT=UN_JTT_IOSV
What I need is
Z-12345
Z-12345
Try this
SUBSTRING(MyCol, (PATINDEX('%[A-Z]-[0-9][0-9][0-9][0-9][0-9]%',[MyCol])),7)
if you run into performance issues add the where clause below
-- from Mytable
WHERE [MyCol] like '%[A-Z]-[0-9][0-9][0-9][0-9][0-9]%'
maybe not the most elegant solution but it works for me.
Correct syntax of PATINDEX
Here's one example how to do it:
select
substring(d.data, s.s, isnull(nullif(e.e,0),2000)-s.s) as ID,
d.data
from data d
cross apply (
select charindex('&ID=', d.data)+4 as s
) s
cross apply (
select charindex('&', d.data, s) as e
) e
where s.s > 4
This assumes there data column is varchar(2000) and the where clause leaves out any rows that don't have &ID=
The first cross apply searches for the start position, the second one for the end. The isnull+nulliff in the actual select handles the case where & is not found and replaces it with 2000 to make sure the whole string is returned.
On the query below I keep getting this error:
Cannot read the next data row for the dataset DataSetProject. (rsErrorReadingNextDataRow)
It appears to be the where clause, if I take it out it seems to work. So I added a cast to the where clause with no luck. Is there something special I need to do in the where clause to get this to work? Just an FYI this is in a report that is pulling an id from the url.
SELECT new_projects.new_projectsId AS ProjectId
, new_projects.new_name AS ProjectName
, new_projects.new_Description AS ProjectDescription
FROM
new_projects
LEFT OUTER JOIN new_projectsteps
ON new_projects.new_projectsId = new_projectsteps.new_ProjectSteps2Id
LEFT OUTER JOIN Task
ON new_projectsteps.new_projectstepsId = Task.RegardingObjectId
WHERE
(new_projects.new_projectsId = cast(#id AS UNIQUEIDENTIFIER))
Thanks!
EDIT:
The id in SQL is a Unique Identifier, the value of #id is being pulled from the querystring(url). So it would look like: &id='BC02ABC0-A6A9-E111-BCAD-32B731EEDD84'
Sorry for the missing info.
I suspect the single quotes are coming through. So either don't have them there by stripping them out before being passed to your parameter or use:
WHERE new_projects.new_projectsId = CONVERT(UNIQUEIDENTIFIER, REPLACE(#id, '''', ''));
If you try a direct comparison when the GUID contains other characters, you should get:
Msg 8169, Level 16, State 2, Line 1 Conversion failed when
converting from a character string to uniqueidentifier.
If this is not what's happening, then don't say "the id in SQL is a Unique Identifier" - show ALL of the code so we can try to reproduce the problem.