Select statement within a select statement - sql

I have the following select statement that returns exactly what I want:
DECLARE #result varchar(max) = ''
SELECT #result += (result.Fullname + '<br/>')
FROM (SELECT DISTINCT Fullname
FROM Providers
WHERE Status='A') as result
select substring(#result, 0, len(#result) - 4)
The only problem is, I want the output from this query to be displayed as a column entry from a larger select statement.
Eg.
SELECT
Column AS [AColumnName],
SELECT #result += (result.Fullname + '<br/>')
FROM (SELECT DISTINCT Fullname
FROM Providers
WHERE Status='A') as result
select substring(#result, 0, len(#result) - 4) as [LenderList]
FROM
Table
But I am currently getting the error: Incorrect syntax near the keyword 'SELECT'.
The error pointing to line 4
Any ideas?

You need aggregate string concatenation in SQL Server. There are already many answers on the subquery, but to save you the trouble:
SELECT Column AS [AColumnName],
STUFF((SELECT DISTINCT '<br/>' + Fullname
FROM Providers
WHERE Status = 'A'
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)'
), 1, 5, ''
) as result
FROM Table;
The use of the type is important because your string has special XML characters.

Can you simply run it in 2 statements?
SELECT #result += (result.Fullname + '<br/>')
FROM (SELECT DISTINCT Fullname
FROM Providers
WHERE Status='A') as result
SELECT
Column AS [AColumnName],
substring(#result, 0, len(#result) - 4)
FROM Table

Which Database? If you can use for xml, then something like...
select substring(a.innards, 0, len(a.innards) - 4) as [LenderList]
from
(
SELECT innards = STUFF(
(SELECT DISTINCT Fullname + '</br>'
FROM Providers
WHERE [Status] = 'A'
FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)')
, 1
, 0
, '')
) a

Related

Insert Result of Select into Variable with Order By

Data
Approval_ID
-----------
1
2
3
4
5
6
7
8
9
10
Query
DECLARE
#id varchar(8000)
SELECT #id = COALESCE(#id + ', ', '') + '[' + Approval_ID + ']'
FROM (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
) Y
Result always
1,10,2,3,4,5,6,7,8,9
I've tried to add Order By
ORDER BY len(Approval_ID), Approval_ID
but have error
The ORDER BY clause is invalid in views, inline functions, derived
tables, subqueries, and common table expressions, unless TOP, OFFSET
or FOR XML is also specified.
and I want to the result like this
1,2,3,4,5,6,7,8,9,10
Whats should I do?
Update :
;with cte as (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
)
SELECT #id = STUFF(
(SELECT concat(',', '[' + Approval_ID + ']')
FROM cte ORDER BY len(Approval_ID), Approval_id
FOR XML PATH('')
), 1, 1, '')
Using CTE and STUFF for XML PATH
-- replace CTE with your table, this is only an example
declare #id varchar(8000)
;with cte as (
select 1 n
union all
select n+1 n from
cte
where n < 10
)
select #id =
STUFF((
SELECT concat(',', n)
FROM cte
order by n
FOR XML PATH('')
), 1, 1, '')
select #id
programmatically cast n from alphanumeric to int for sorting
It seems you are using a varchar field instead of an integer for Approval_ID.
For ordering it based on the varchar field, you can try the method from maSTAShuFu's answer.
Here I am updating it with your query from question.
SELECT STUFF(
(SELECT CONCAT(',[', Approval_ID,']')
FROM <your_table>
ORDER BY cast(Approval_ID as int)
FOR XML PATH('')), 1, 1, '')
Maybe you can try to convert varchar to int for this purpose. I built an example here
DECLARE
#id varchar(8000)
SELECT #id = COALESCE(#id + ', ', '') + '[' + CAST(ID AS VARCHAR(10)) + ']'
FROM (
SELECT DISTINCT CAST(id AS INT) ID
FROM TABLA
) Y
SELECT #ID

Concatenate column values based on type result

Declare #name nvarchar(max),#Id int
SELECT #Id=[EmpType],#name =ISNULL(#name + ',','')+[UserName] FROM [dbo].[TestTable]
Group by [EmpType]
SELECT #Id,#name
Getting error with this code, How can i get the result employee type wise concatenated usernames
Expecting Result set
You can try below using STUFF() function
SELECT [EmpType], abc = STUFF(
(SELECT ',' + [UserName]
FROM [dbo].TestTable] t1
WHERE t1.[EmpType] = t2.[EmpType]
FOR XML PATH (''))
, 1, 1, '') from [dbo].TestTable] t2
group by [EmpType];

How to combine two rows with comma separator in sql server 2008

I tried as shown below
SELECT SUBSTRING(
(
SELECT td.Text + ', ' AS 'data()',
Tda.FirmID
FROM tblData1 tda
INNER JOIN tblData2 Td
ON Tda.ID = Td.ID
GROUP BY
Tda.Enable1,
Tda.ID,
Td.Text
HAVING ISNULL(Enable1, 0) = 1
FOR XML PATH('')
),
1,
10000
) AS Csv
Output:
Landlord Tenant, <FirmID>1</FirmID>NJ Traffic, <FirmID>1</FirmID>
Expected Output: Should be in table format
csv FirmID
Landlord Tenant, NJ Traffic 1
I got the results by using COALESCE
DECLARE #Text VARCHAR(MAX)
DECLARE #ID NUMERIC(18,0)
SELECT #Text = COALESCE(#Text + ', ', '') +
CAST(td.Text AS VARCHAR(MAX)),#ID = MAX(tda.FirmID)
FROM tblData1 tda
INNER JOIN tblData2 Td
ON Tda.ID=Td.ID
GROUP BY
Tda.Enable,
Tda.FirmID,Td.Text
HAVING ISNULL(Enable,0)=1
SELECT #Text AS Text,#ID AS ID
OutPut:
text ID
Landlord Tenant, NJ Traffic 1
Leave out the aliases in the subquery and try this:
SELECT STUFF((SELECT ', ' + td.Text
FROM tblData2 Td
WHERE ISNULL(Enable1, 0) = 1
FOR XML PATH('')
), 1, 2, '') AS Csv,
MAX(Tda.FirmID)
FROM tblData1 tda;
You cannot select multiple columns in the subquery either. After all, the purpose is to combine values into a single column. Multiple values in the select create one column, but with multiple XML tags within the string.
You also do not need the group by in the subquery.

Split the query string with repeatative special characters using SQL

This is my String
Declare #qstr as varchar(max)='hireteammember.aspx?empemail=kuldeep#asselsolutions.com&empid=376&empname=kuldeep&adminname=TMA1&term=5&teamid=161&contactid=614¥1&WP=100¥5¥Months&Amt=500&DueDay=5&StrDt=12/31/2013&MemCatg=Employees&StrTm=21:05&PlnHrs=5&WrkDays=true¥true¥true¥true¥true¥false¥false'
I want to extract the values of empid,empname,adminname,term,teamid,contactid,WP,Months,Dueday,StrDt,MemCatgmStrTm,PlnHrs,WrkDays and assign them to new variables
I have used
select ( SUBSTRING(#qstr,CHARINDEX('=',#qstr)+1,CHARINDEX('&',#qstr)-CHARINDEX('=',#qstr)-1)))
but only getting the 'empemail' , for the next occurance of special char '&' , not able to get the values of further terms , if i am using '&' in spite of '=' .
Help me to split the whole string
How about using XML to split the values into rows, and then splitting them into columns.
Something like
Declare #qstr as varchar(max)='hireteammember.aspx?empemail=kuldeep#asselsolutions.com&empid=376&empname=kuldeep&adminname=TMA1&term=5&teamid=161&contactid=614¥1&WP=100¥5¥Months&Amt=500&DueDay=5&StrDt=12/31/2013&MemCatg=Employees&StrTm=21:05&PlnHrs=5&WrkDays=true¥true¥true¥true¥true¥false¥false'
DECLARe #str VARCHAR(MAX) = SUBSTRING(#qstr,CHARINDEX('?',#qstr,0) + 1, LEN(#qstr)-CHARINDEX('?',#qstr,0))
DECLARE #xml XML
SELECT #xml = CAST('<d>' + REPLACE(#str, '&', '</d><d>') + '</d>' AS XML)
;WITH Vals AS (
SELECT T.split.value('.', 'nvarchar(max)') AS data
FROM #xml.nodes('/d') T(split)
)
SELECT LEFT(data,CHARINDEX('=',data,0) - 1),
RIGHT(data,LEN(data) - CHARINDEX('=',data,0))
FROM Vals
SQL Fiddle DEMO
CREATE FUNCTION dbo.SplitQueryString (#s varchar(8000))
RETURNS table
AS
RETURN (
WITH splitter_cte AS (
SELECT CHARINDEX('&', #s) as pos, 0 as lastPos
UNION ALL
SELECT CHARINDEX('&', #s, pos + 1), pos
FROM splitter_cte
WHERE pos > 0
),
pair_cte AS (
SELECT chunk,
CHARINDEX('=', chunk) as pos
FROM (
SELECT SUBSTRING(#s, lastPos + 1,
case when pos = 0 then 80000
else pos - lastPos -1 end) as chunk
FROM splitter_cte) as t1
)
SELECT substring(chunk, 0, pos) as keyName,
substring(chunk, pos+1, 8000) as keyValue
FROM pair_cte
)
GO
declare #queryString varchar(2048)
set #queryString = 'foo=bar&temp=baz&key=value';
SELECT *
FROM dbo.SplitQueryString(#queryString)
OPTION(MAXRECURSION 0);
when run produces the following output.
keyName keyValue
------- --------
foo bar
temp baz
key value
(3 row(s) affected)
I believe that this will do exactly what you are asking.
SQL FIDDLE DEMO
If the order of the values in the html string remains same i would suggest using the whole string name like
select ( SUBSTRING(#qstr,CHARINDEX('empemail=',#qstr)+1,CHARINDEX('&empid=',#qstr)-CHARINDEX('empemail=',#qstr)-1)))
If you are still looking for nth occurance then refer to this link
Declare #qstr as varchar(max)='hireteammember.aspx?empemail=kuldeep#asselsolutions.com&empid=376&empname=kuldeep&adminname=TMA1&term=5&teamid=161&contactid=614¥1&WP=100¥5¥Months&Amt=500&DueDay=5&StrDt=12/31/2013&MemCatg=Employees&StrTm=21:05&PlnHrs=5&WrkDays=true¥true¥true¥true¥true¥false¥false'
(select ( SUBSTRING(#qstr,CHARINDEX('&empname=',#qstr)+1,CHARINDEX('&adminname=',#qstr)-CHARINDEX('&empname=',#qstr)-1)))
(select ( SUBSTRING(#qstr,CHARINDEX('?empemail=',#qstr)+1,CHARINDEX('&empid=',#qstr)-CHARINDEX('?empemail=',#qstr)-1)))
like this i have splitted and updated The whole string. Thank you All for your answers, Your answers Helped me to solve this

Flatten SQL Server Table to a string

I have a table like:
ID | Value
----------------
1 | One
2 | Two
3 | Three
What I need to do is create a single string from these values, in the format:
'1: One, 2: Two, 3: Three'
I know how to do this using cursors, but it will be used as a column in a view, so it's not really a performant option.
Any pointers?
WITH T(ID,Value) AS
(
SELECT 1, 'One' UNION ALL
SELECT 2, 'Two' UNION ALL
SELECT 3, 'Three'
)
SELECT STUFF(
(SELECT ', ' + CAST(ID as varchar(11)) + ': ' + Value
FROM T
FOR XML PATH (''))
, 1, 2, '')
Have a look at something like
DECLARE #Table TABLE(
ID INT,
Value VARCHAR(20)
)
INSERT INTO #Table SELECT 1,'One'
INSERT INTO #Table SELECT 2,'Two'
INSERT INTO #Table SELECT 3,'Three'
SELECT STUFF(
(
SELECT ', ' + CAST(ID AS VARCHAR(MAX)) + ': ' + Value
FROM #Table
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
)
SELECT STUFF((
SELECT ' ' + CAST(ID AS VARCHAR(2)) + ': '+ Value
FROM dbo.Table
FOR XML PATH('')
), 1, 1, ''
) As concatenated_string
DECLARE #ans VARCHAR(max)
SET #ans=''
SELECT #ans = #ans + str(id)+':'+value FROM table
SELECT #ans
Change the max to 8000 if your version of SQL doesn't support it
I would simply not do this in the database if at all possible. It's not designed for formatting data in a certain way; let the calling application handle that.
In C# (assuming data is an instance of SqlDataReader):
var l = new List<string>();
while (reader.Read())
l.Add(string.Format("{0}: {1}", reader[0], reader[1]));
var s = string.Join(", ", l.ToArray());