I have a SQL stored procedure that will return only one record. However, in that proc, is a subquery, that can return more then one rows. I believe it might be best design the sub query to return one row of multiple columns, instead of multiple rows.
How would I write out the sub query so it returns columns.
Currently the query is:
SET @Pkg_Status = (Select lf.name, edi.Date from EdiPackage edi, Labelfeed lf
Where edi.orderID = @OrderID
AND edi.code = lf.code
AND lf.labelID = 'EDIStage')
A sample resultset from the above query would be:
Column 1 Column 2 Field1.Value1 Field2.Value1 Field1.Value2 Field2.Value2 Field1.Value3 Field2.Value3
Instead, I would like the results to be:
Column 1 | Column2 | Column3 | Column4 | Column 5 | Column 6 Field1.Value1 | Field2.Value1 | Field1.Value2 | Field2.Value2 | Field1.Value3 | Field2.Value3
How can this be done?
First, you should use the ISO Join keyword when joining two tables instead of separating the tables via comma and then “joining” them in the Where clause. So our query would be:
Second, your original example is setting the results of a query to a variable. That will not work with multiple columns or rows. At best, SQL might simply take the first column in your subquery. Lastly, what it sounds like you seek is something of a crosstab. We would need to see the data, but you can achieve what you want by doing something like so:
In this case, you would replace ‘Value1’, ‘Value2’ and ‘Value3’ with the data values that should be used to differentiate one column from another.