Create function concatenate

I want to know How I can create a function that will concatenate fields
ex: UF_Concat_fields (Tbl_Name, Field_Name, Where_Clause, Separ_Char)

In that function, I could do select Field_Name from tbl_Name  where 
Where_Clause in a cursor or something like that and add the Separ_Char which 
would = ", ".

ex: UF_Concat_fields ("tbl_colors", "Desc", "chk_active = 1", ', ')
the Result would be "Red, Blue, Green, Yellow"


ex: UF_Concat_fields ("tbl_numbers", "Desc", "id1 < 20", ' - ')
the Result would be "One - two - three - ten"

Thanks
Steph 


0
Steph
6/7/2010 3:43:49 PM
sqlserver.programming 1873 articles. 0 followers. Follow

6 Replies
928 Views

Similar Articles

[PageSpeed] 48

To accomplish this you would need dynamic SQL and it cannot be used in
functions. However, you can create a stored procedure.

A couple references:
Dynamic SQL: http://www.sommarskog.se/dynamic_sql.html
Dynamic search conditions: http://www.sommarskog.se/dyn-search.html
Concatenation (look for the XML PATH method):
http://www.projectdmx.com/tsql/rowconcatenate.aspx

-- 
Plamen Ratchev
http://www.SQLStudio.com
0
Plamen
6/7/2010 4:34:36 PM
I created the dynamic stored procedure but it is useless... I can't use it 
in my select statement like I can do in a function...
My stored procedure always returns a varchar(4000) field containing the 
values concatenated.

Exec SP_Concat_Fields('MyTbl', 'MyFld', 'Where Code = ''A''', 'Order By ID')
This returns the following: "One, Two, Three, Four, Five"

It is not possible that Microsoft never thought about using a stored 
procedure in a select statement...
I found the Openrowset function but it seems dangerous for security reason 
to activate the "Ad Hoc Distributed Queries"

Any other way which is safe?

Steph

"Plamen Ratchev" <Plamen@SQLStudio.com> wrote in message 
news:on7q06hsqgklt0401acc57j51novsophmr@4ax.com...
> To accomplish this you would need dynamic SQL and it cannot be used in
> functions. However, you can create a stored procedure.
>
> A couple references:
> Dynamic SQL: http://www.sommarskog.se/dynamic_sql.html
> Dynamic search conditions: http://www.sommarskog.se/dyn-search.html
> Concatenation (look for the XML PATH method):
> http://www.projectdmx.com/tsql/rowconcatenate.aspx
>
> -- 
> Plamen Ratchev
> http://www.SQLStudio.com 


0
Steph
6/11/2010 1:40:09 PM
Steph (smarcoux@cbgi.qc.ca) writes:
> I created the dynamic stored procedure but it is useless... I can't use it 
> in my select statement like I can do in a function...
> My stored procedure always returns a varchar(4000) field containing the 
> values concatenated.
> 
> Exec SP_Concat_Fields('MyTbl', 'MyFld', 'Where Code = ''A''', 'Order By
> ID') This returns the following: "One, Two, Three, Four, Five" 
> 
> It is not possible that Microsoft never thought about using a stored 
> procedure in a select statement...


Permitting that is non-trivial, since a stored procedure can return
a result set in different shape each time.

Rather trying to answer your question, I would suggest that you tell
us the full story what you are trying to achieve, because I get a 
feeling that you are off-track entirely.


-- 
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

0
Erland
6/11/2010 10:22:57 PM
The full story...

I have a client who wants a lot of reports and a lot of views.

almost every view contains a table containing multiple values for the same 
record... ex: categories... a client can be linked to an indefinite number 
of categories.
When we look at the report, we don't want to see 5 rows for the same client 
if it is linked to 5 categories. One row max. But we want to see the 5 
categories in one field.

That's why I createde a stored procedure which  concatenates a field or 
expression from a view/table and it returns one varchar(4000) field. I use 
some parameters (tbl_name, fld_name, where_clause, order_by_clause). I f for 
one view I need to see the category code, I use "Code" for fld_name and if I 
need to see the description, I use "Categ_Desc".
The stored procedure is working fine when I use exec but I want to use it in 
a view like I would do with a function. I know that I could create 
subqueries each time to concatenate the data but I wanted to lose less time 
doing something that 's already done several times. I don't want to have 200 
functions for every concatenation possibilities they ask me.

I hope that the full story helps you understanding my need.

thanks

Steph


"Erland Sommarskog" <esquel@sommarskog.se> wrote in message 
news:Xns9D953E467F1BYazorman@127.0.0.1...
> Steph (smarcoux@cbgi.qc.ca) writes:
>> I created the dynamic stored procedure but it is useless... I can't use 
>> it
>> in my select statement like I can do in a function...
>> My stored procedure always returns a varchar(4000) field containing the
>> values concatenated.
>>
>> Exec SP_Concat_Fields('MyTbl', 'MyFld', 'Where Code = ''A''', 'Order By
>> ID') This returns the following: "One, Two, Three, Four, Five"
>>
>> It is not possible that Microsoft never thought about using a stored
>> procedure in a select statement...
>
>
> Permitting that is non-trivial, since a stored procedure can return
> a result set in different shape each time.
>
> Rather trying to answer your question, I would suggest that you tell
> us the full story what you are trying to achieve, because I get a
> feeling that you are off-track entirely.
>
>
> -- 
> Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
>
> Links for SQL Server Books Online:
> SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
> SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
> SQL 2000: 
> http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
> 


0
Steph
6/14/2010 2:00:33 PM
>> I hope that the full story helps you understanding my need. <<

This is a very common newbie design error. The give-away was when you
did not know that fields and columns are totally different.

You want to format data in the database, thus destroying First Normal
Form (1NF) and a tiered architecture. The right way to do this is to
use a report writer. There is a good chance that your client has a
copy of reporting services, owns a copy Crystal Reports (or other
commercial packages) or can get some Open Source tool. Do not saw wood
with a hammer.

When I did queries like this, we had to prioritize the categories. It
was in a Prison system, so it was more important to see that an inmate
was a serial murderer than to see his shoplifting convictions.

This is easy to do in a query since the Criminal Code is a hierarchy
-- like Dewey Decimal number for evil :)  I hope that you also took
the time to design the encoding schemes for the client's categories.
0
CELKO
6/14/2010 4:25:09 PM
Steph (smarcoux@cbgi.qc.ca) writes:
> almost every view contains a table containing multiple values for the same 
> record... ex: categories... a client can be linked to an indefinite number 
> of categories.
> When we look at the report, we don't want to see 5 rows for the same
> client if it is linked to 5 categories. One row max. But we want to see
> the 5 categories in one field. 
> 
> That's why I createde a stored procedure which  concatenates a field or 
> expression from a view/table and it returns one varchar(4000) field. I
> use some parameters (tbl_name, fld_name, where_clause, order_by_clause).
> I f for one view I need to see the category code, I use "Code" for
> fld_name and if I need to see the description, I use "Categ_Desc". The
> stored procedure is working fine when I use exec but I want to use it in
> a view like I would do with a function. I know that I could create 
> subqueries each time to concatenate the data but I wanted to lose less
> time doing something that 's already done several times. I don't want to
> have 200 functions for every concatenation possibilities they ask me. 

If you want some generic function, you could write a user-defined
aggregegate using the CLR. But beware that there is no way to have
the lists be ordered if you go this route.

Else, you will have to write subqueries using FOR XML PATH, as 
descrubed on http://www.projectdmx.com/tsql/rowconcatenate.aspx.

-- 
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

0
Erland
6/14/2010 9:55:50 PM
Reply:

Similar Artilces:

calling a public function correctly
I can’t figure out how to run this for the life of me. Trying to run a function that updates the combo boxes for all open forms. Here is what I have with asterisks marked on what I think is the problem line. Have tried many permutations and gotten all sorts of new and exciting errors but none that has worked right yet. Sub AllForms() Dim obj As AccessObject, dbs As Object Set dbs = Application.CurrentProject ' Search for open AccessObject objects in AllForms collection. For Each obj In dbs.AllForms If obj.IsLoaded = True Then *******What goes here to call the r...

create a roster
How can you create a weekly roster in which functions can be assigned to more than 10 people. The roster should be updatable, so that when holidays and days off are marked on the weekly roster they will be taken account of it future rosters. ...

importing or creating reference footnotes
I am trying to import a word document into publisher and it has reference footnotes within the document. The reference footnotes are not coming into the publisher document with the reference footnotes. Correct, they will not up to Publisher 2003. In Publisher 2003 depending on which version of Word you are using if they will or not. -- "If you don't know where you are going, any road will take you there!" ...

Mailbox not created when AD account created
A couple of days ago I noticed that I created a user account but the 'Email Addresses' tab of the user properies did not list any email addresses. Subsequent new user accounts have all experienced the same. I researched the knowledge and tried the recommended solutions to either manaully start the recipient update service or rebuild te recipient update service. Neither recommendation has resulted in a mailbox being created for this particular user or any additional user that I have created since this error first showed up. I performed a Windows update last Thursday and so I bel...

how to call drawitem() function in ower draw Clistbox
Another question about ower-draw listbox: I created an ower-draw Listbox and override the drawitem(LPDRAWITEMSTRUCT lpDrawItemStruct) function. Is there any way to refresh the listbox by calling DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) after the user click on a button? Thanks, Eileen > Another question about ower-draw listbox: I created an ower-draw > Listbox and override the drawitem(LPDRAWITEMSTRUCT lpDrawItemStruct) > function. Is there any way to refresh the listbox by calling > DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) after the user click on a > button? > Ca...

Task Create - Status
I'm trying to make a simple task, when a user owner is assigned a task in CRM, it receives an email letting it know it has one. I have the following below, but it is not generating one when i assign one manually in the CRM. What to do? I've tried both the following: When task is created E-Mail to:[owner];Subject test As well as: When task is created if Task activity status = Open then E-Mail to:[owner];Subject test I've checked the mailserver many times over, and I can send emails manually from the CRM so you can rule that out Tested out ok on our end. Some ideas:...

Help Creating XmlNode / XmlAttribute Elegantly
I am creating a configuration class to read / write a standard configuration file. <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="ConnectionString" value="server=(local);" /> </appSettings> </configuration> I am using a XmlDocument for my base implementation. I am looking to see if there is a better way to add a new node / attribute than using XmlDocument.InnerXml. I would consider this to be a hack but couldn't really see another way of doing this without definin...

Create external database
Hi all. I need to create an external database (file). On a site I found this code: ------------------------------------------------------ Function CreateLinkedExternalTable(strTargetDB As String, strProviderString As String, strSourceTbl As String, strLinkTblName As String) As String 'strTargetDB = Source Database Name 'strProviderString = Not used, currently hard coded 'strSourceTbl = Source Table name in the database we are linking too. 'strLinkTblName = Table name we would like to see in the Access Database. Dim catDB As ADOX.Catalog Dim tblLink As...

simple yet nagging issue with functions and "format cells"
i'm sure this is a really simple issue...my knowledge of excel is not comprehensive, it's all self-taught and very specific (i.e. i have a great deal of knowledge on some stuff and other stuff i've never used). i have a spreadsheet with five worksheets in it, and it's not letting me type in any functions or alter the formatting of cells. essentially the sticking point is there is a column of zip codes that has lost its leading zero, and i'm trying to either concatenate it with a leading zero or change the box format to zip code. no luck on either. if i type in any formula,...

How to create pie chart with %
I have got a problem that I don't if excel could help me to calculate the % within a column and draw a pie chart. My case is I have a column containing a series of numbers. e.g. 1,4,8,1,3,9,11,2,4,5,6,.........etc I want to draw a pie chart that showing 1-3 , 4-6, 7-9, >9 with the corresponding % inside that column. Can anyone tell me how can I make it ? Ray - You need to calculate the frequencies in your data. Let's assume your data is in A1:A12. In B1:B3 enter these numbers, the upper limits on the groupings: 3 6 9 You can enter ">9" into B4 witho...

Excel Function Problem
Hi, Please consider me an excel newbie! I am trying to find out how to write a function that checks a 7 digit numerical string entered into cell i.e. 7030000 against 50 possible strings. (Im guessing this is a multiple IF statement thing). Once the condition is true it then takes the value from cell J7, adds it to the value in cell D7. The end result being that D7 now contains a value equal to its original value + J7. Any help given would be appreciatted Many Thanks --- Message posted from http://www.ExcelForum.com/ You might look at the SumIF function. It will add values together if...

Email address not created when a new user is created
All, This issue recently happened in my company. Upon creating a new user, the policy was set to create the smtp and X400 address automaticaly. Now when we create a user the smtp and x400 addresses are not created, and when attempting to setup the new user in outlook, the address cant be found. We are using exchange 2003 SP1 on Win2k3 servers. On Wed, 13 Jul 2005 06:49:07 -0700, "Bryan" <Bryan@discussions.microsoft.com> wrote: >All, >This issue recently happened in my company. Upon creating a new user, the >policy was set to create the smtp and X400 addres...

Exchange 2010 MRM, no log files being created
I'm hoping someone can help me with this issue....it has been driving me crazy for days. I have enabled MRM logging on our exchange server, and I can see that some of the policies are working when I run start-managedfolderassistant. We have a retention policy tag on the deleteditems folder, and this does work. The problem is I am not getting any files in the MRM log directory. C:\Program Files\Microsoft\Exchange Server\V14\Logging\Managed Folder Assistant Events 9021 and 9022 are logged in the Application log, but where are the files? Below is the output of my mai...

when form created
I have a form which was created by someone else (not a form template) which is like a questionnaire with empty boxes to be completed. When the boxes are typed in all the margins move to accommodate the words being typed. Is there a way to fix/lock the original form and then just fill in the blank boxes? I suspect this is set up as a table with auto resizing enabled. Displaying table gridlines (Table | Show Gridlines) will help you see what you're dealing with. Then select the table, go to the Table tab of Table Properties, click Options, and clear the check box for "A...

Set Function Keys
Hello All! I'm trying to set the function keys with me.KeyPrewiew and on KeyDown. I realized that it doesn't work all the time, because of the default settings. for example F1 key will display Help many times, even I set it to something else. Is there a way to set the vbKeyF1 or the rest of the keys, and disable the default setting? Thanks in advance Abe The KeyDown event of the *form* should work (with KeyPreview on.) To suppress the normal use of the key, destroy the keystroke with: KeyCode = 0 If you wanted something application-wide (not just for one form), you could...

Creating a Brochure
How do you create a 3-column brochure from scratch for Publisher 2002? I can only find the directions for the 2003 version. Quick help would be appreciated, project is due Monday. Create a three-panel or four-panel folded publication http://office.microsoft.com/en-us/assistance/HP011646681033.aspx Scroll down to the section that says "Build a three-panel or four-panel publications from scratch." -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.microsoft.com "Derek" <Derek@discussions.microsoft.com> wrote in message news...

How to create Access macro shortcut
I'm still using Access 97 and saw something the other day that I would like to use that was in Access 2000. In an Access 2000 database, there was a .mam file in a directory that launched the Access 2000 program and ran a macro. How do you set this up? Can it be done in Access 97? If so, how? Hi. > How do you set this up? Select the macro in the Database Window and right click with your mouse, then select "Create Shortcut..." in the pop-up menu. Follow the prompts for where to place the shortcut and what to name it. The default is: <PathToDeskTopDir>\Shortcut ...

need opposite of MODE function in Excel
How do I find the number that occurs LEAST frequently in a range of numbers? This is the exact opposite of the MODE function, which finds the most common occurrence. For example, a column of numbers contains; 2 4 5 2 4 2 MODE will return "2" as the most commonj occurrence. I want to know that "5" is the least common occurence. Obviously, my column contains many more numbers so it's not easily to simply visualize and count them. Is there a way to do this in Excel? Thanks. Hi Kevin, You can do that with the Frequency function. data freq bins 2 0 1 ...

Users mailboxes not created when user created
I have a problem that recently just started happening on my exchange 2003 server. When i create a new user account and create the mailbox for exchange, once im done, the mailbox isnt created, adn if you go into the properties of the user account adn go to the exchange email address tab, there isnt an smtp or an x.400 address listed. I am having to manually create and add these, adn then go delete the exchange mailbox and recreate it. This is really annoying and would love to know if anyone has any ideas of how to fix it. Thanks Jason In news:9F836A43-98BF-435A-AA43-AFF10124BE3F@micro...

functional level
Do I have to raise my functional level to 2003 in my domain in order to install exchange 2003! Or could I do that after? What is the best approach? Thanks in Advance "Juan" <anonymous@discussions.microsoft.com> wrote: >Do I have to raise my functional level to 2003 in my >domain in order to install exchange 2003! Or could I do >that after? > >What is the best approach? > > >Thanks in Advance You can run E2K3 in W2K Mixed mode if you want. The Windows mode doesn't have much of a functional bearing on the operation of Exchange. If you'v...

CRM should let me create custom fields in batch
Hi, With MS CRM v3.0, when we have a group of fields to create, it would be faster to be able to enter the list and then submit the list for processing. Thank you. Felix. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssolutions/C...

Creating an ad book
How do I divide a page into equal sections (halves, qarters, eights)? I need to scan and type ads and coupons into this booklet. New at this. After managing to set up OE-QuoteFix on his new PC, Ed reads a message from FRSH <anonymous@discussions.microsoft.com>... > How do I divide a page into equal sections (halves, qarters, eights)? Arrange > Layout Guides > Grid Guides -- Ed Bennett - MVP Microsoft Publisher http://www.mvps.org/the_nerd/ Before reading this message, view the disclaimer: http://mvps.org/the_nerd/disclaim.htm ...

Access unable to create an MDE
I am getting this message when I try to make an MDE: "Access unable to create an MDE database" No error mesages or any other info is displayed. I haven't had this trouble before. Then I added a form, a couple reports, an create table query, modified a toolbar and added a module. Now I am getting this message. This database is a front end of a project with several linked table to a back end. Any suggestions? Thanks Jeff G Try compiling your application (under the Debug menu when you're in the VB Editor). Often an application will have some error that doesn't m...

create a database from which bibliography an be created
How do I create a database from which a bibliography can be added to the end of a Word document? I used the program RefManager, but that is too expensive for me to update. Does Word 2003 have such a program? Thanks Not natively. Have you checked your academic institution? They might have campus licenses which students can use at home. You could give Zotero a spin (www.zotero.org). Personally, I don't like it, but that's just me. Word 2007 comes with referencing capabilities, but they are limited in functionality. Anything special you want, you would have to add i...

Error creating activities from Cases
Hi I have an out of the box SBS 2003 CRM Setup I have installed Rollup1 and the new help files Under about MS CRM it has CRM 3.0 (3.0.5300.0) When we try and create activies from within a case, we get the following to errors in the event log We can create the activities just fromthe main web client menu ok The same thing happens in the outlook client (OL 2003, Exchange 2003) I found some links to verabose stuff, but they all applied to the have MS CRM setup on multiple server. We have tried it with and without Outlook open Anyhelp appreciated Event Type: Error Event Source: MSC...