|
|
|||||||||
|
|||||||||
|
|||||||||
| |
||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
SQL Aggregate function that combines like CONCAT
Hey all,
I'm trying to find a way to query a database, using several GROUP BY's, but I need the IDENTITYCOL to be put in an aggregate function that will give me a string representation of each IDENTITYCOL value. Something in between a SUM and a CONCAT. So basically if I have records with IDENTITYCOL's 1, 3, 4 and 5, I'd like to be able to call THISFUNCTION(IDENTITYCOL) AS Expr1 and get Expr1 to be "1,3,4,5". Is there anything remotely like this? Thanks! |
|
#2
|
||||
|
||||
|
Try something like this:
declare @result varchar(8000) set @result = '' select @result = (case when @result = '' then cast(id as varchar(16)) else @result + ',' + cast(id as varchar(16)) end) from sysobjects select @result |
|
#3
|
|||
|
|||
|
Thanks very much! I'm having trouble getting it to be more useful though. I want to accept 3 arguments: @table, @column, and @where. Table being the @table selected from, @column being the column, and @where being a condition. I'm getting 'Error 156: Incorrect syntax near the keyword 'return'"
Code:
CREATE FUNCTION [dbo].[fnGroup_Concat] (@table varchar(50), @column varchar(50), @where varchar(50)) RETURNS varchar(8000) AS BEGIN declare @result varchar(8000) set @result = '' select @result = (case when @result = '' then cast(@column as varchar(16)) else @result + ',' + cast(@column as varchar(16)) end) from [@table] where @where return @result END |
|
#4
|
||||
|
||||
|
You should use the "dynamic" SQL, like:
declare @cmd varchar(8000) set @cmd = 'declare @result varchar(8000) set @result = '''' select @result = (case when @result = '''' then cast(@column as varchar(16)) else @result + '','' + cast(@column as varchar(16)) end) from [' + @table + '] where ' + @where exec(@cmd) But you can't use EXECUTE within a function. Why function, not stored procedure? |
![]() |
| Viewing: ASP Free Forums > Database > Microsoft SQL Server > SQL Aggregate function that combines like CONCAT |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|