Splitting A Comma Seperated Column Into Multiple Rows

Jan 18, 2006

Hi i want to create a table as follows :

if exists (select * from dbo.sysobjects where id =
object_id(N'[Indexes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [Indexes]
GO

Create table Indexes(indexname Varchar(100), index_Description
Varchar(100), index_keys Varchar(100))
GO

INSERT INTO Indexes EXEC sp_helpindex 'SDM_Fact_Order_Detail'
GO

This will give me a table (northwind)

IX_Auto_SDM_Fact_FK_Shipped_Date nonclustered located on
SAMIS_SDM_Index FK_Shipped_Date

IX_Auto_SDM_Fact_Order_Detail_FK_Insert_Dateclustered located on
SAMIS_SDM_Data1FK_Insert_Date, FK_Insert_Time

As you see sp_helpindex will give me a comma seperated field. I want
to split the third column FK_Insert_Date, FK_Insert_Time into a extra
row
Like this :

IX_Auto_SDM_Fact_FK_Shipped_Date FK_Shipped_Date
IX_Auto_SDM_Fact_Order_Detail_FK_Insert_Date FK_Insert_Date
IX_Auto_SDM_Fact_Order_Detail_FK_Insert_Date FK_Insert_Time

Can anyone help me with this?

Thanx

Hennie

View 1 Replies


ADVERTISEMENT

Report Designer: Need To List Fields From Multiple Result Rows As Comma Seperated List (like A JOIN On Parameters)

Apr 9, 2008



I know I can do a JOIN(parameter, "some seperator") and it will build me a list/string of all the values in the multiselect parameter.

However, I want to do the same thing with all the occurances of a field in my result set (each row being an occurance).

For example say I have a form that is being printed which will pull in all the medications a patient is currently listed as having perscriptions for. I want to return all those values (say 8) and display them on a single line (or wrap onto additional lines as needed).

Something like:
List of current perscriptions: Allegra, Allegra-D, Clariton, Nasalcort, Sudafed, Zantac


How can I accomplish this?

I was playing with the list box, but that only lets me repeat on a new line, I couldn't find any way to get it to repeate side by side (repeat left to right instead of top to bottom). I played with the orientation options, but that really just lets me adjust how multiple columns are displayed as best I can tell.

Could a custom function of some sort be written to take all the values and spit them out one by one into a comma seperated string?

View 21 Replies View Related

Field Contains Multiple Values Seperated By Comma

May 3, 2006

Hi All

I'm really new to SQL and would appreciate a solution to the following problem.

I have a table that contains 1 record. in that record there is a column called CODES which contains multiple values that are seperated by a comma.

C200,C201,C202,C204,C200,C203,C200,C202,C203,C205,C200,C202,C203,C204,C205,C206,C200,C201,C202

I need a solution to select all values from CODES that are distinct so I end up with the following.

C200,C201,C202,C203,C204,C205,C206

Any help would be really appreciated. Please bear in mind I'm a complet novice.

View 4 Replies View Related

Extracting Multiple Values As Comma Seperated

Jul 17, 2007

Hi all,



This is my table :

WorkstationNo UserID

101 a1

102 a2

103 a3

101 a2



and there are many other fields too. The output I need is something like this



WorsktationNo OccupiedBy

101 a1,a2

102 a2

103 a3



In the similar fashion I would also require to retrieve the values based on the UserID something like this

UserID Workstations

a1 101

a2 101,102

a3 103



Could someone tell me how to write the query for this.



View 9 Replies View Related

Select Multiple Rows In One Column With Comma

Jul 26, 2013

CREATE TABLE [dbo].[x1](
[nomer] [varchar](15) NOT NULL,
[tgl] [datetime] NOT NULL,
CONSTRAINT [pk_x1] PRIMARY KEY CLUSTERED
(
[nomer] ASC,

[Code] ....

Result :
nomer tanggal
12013-07-28 00:00:00.000
12013-07-29 00:00:00.000
12013-07-30 00:00:00.000

I Want to make :
nomer tanggal
1 28,29,30

View 2 Replies View Related

Splitting A Comma Delimited Column

Feb 12, 2008



Hi

I wondered if anyone could help me. I have a table that holds an ID in the first column then a list of values split by commas in the 2nd column i.e.:

IDColumn: 1
2ndCoumn: 1stvalue, 2ndvalue, 3rdvalue, 4thvalue

I am trying to return as a dataset of this that shows the ID as column 1 then each value in the 2nd column as individual columns if I use SELECT LEFT('2ndColumn,PATINDEX(',',2ndColum)-1) I can return the first value as a column but then can't return any further values individually after the first column, I am just learning the new functionality in SSIS so not sure whether this would be my answer as apposed to T-SQL, if anyone has any advice on this it would be greatly appreciated?

Thanks in advance

Caralyn

View 7 Replies View Related

Transact SQL :: Get Multiple Rows Based On Comma-separated Ntext List In On Column?

Jun 2, 2015

I have a table that is used to build rules. The rules point to other columns in other tables and usually contain only one value (i.e. ABC). But one of the options is to add a comma-separated list of SSNs (i.e. 123123123,012012012,112231122).  I am trying to build a single query that allows me to leverage that list to get multiple rows from another table.

This obviously works:

SELECT * FROM vw_Person_Profile P (NOLOCK)
WHERE P.PrsnPIISSN_Chr IN ('123123123','012012012','112231122')

But this does not:

SELECT * FROM vw_Person_Profile P (NOLOCK)
WHERE P.PrsnPIISSN_Chr IN (
SELECT '''' + REPLACE(CONVERT(VARCHAR(4000),txtFieldValue), ',', ''',''') + ''''
FROM MassProcessing_Rules PR
WHERE PR.intRuleID = 10
)

View 5 Replies View Related

T-SQL (SS2K8) :: Splitting Row Into Multiple Rows

May 14, 2015

I have a table that has for example data

I am looking to write a script that will change the first table into the second table.......

Table 1

Account No Name other field
1 Mr T and Mrs M Lambert xxx

I need to rewrite this as

Table 2

Account No split Name other field
1 a Mr T Lambert xxx
1 b Mrs M Lambert xxx

View 9 Replies View Related

SQL Comma Seperated List

Jul 26, 2005

Is there a way to return a comma seperated list in a  query?For example if I have this simple querySelect member_name From members It returns all the members in diff rows (lets assume we have 3)So the result will bemember_name--------------name1name2name3Instead of this I need to have the result in one row with values seperated by commas.member_name---------------name1,name2,name3I hope I am clear enough. Any help would be appreciated. Thank you.

View 4 Replies View Related

Comma Seperated Values

May 5, 2008

What is the best way? I have a field of comma seperated article type id values in a users profile. This list is a set of values that sows the article types the person does NOT want to see. Each article has an article type id. I need to do a select joining the article table to the member table that only shows those article id's that are not in the comma seperated list. How would I do that in a sql statement?

View 3 Replies View Related

Comma Seperated Select

May 14, 2008

Not sure the best way to do this. They are passing in a comma seperated string. I have a field that has comma seperated strings in it. I need to compare the 2 strings and do a select on that field that has any of the words in the string passed in. So if the pass...
"car,boat,van"

and in the field 2 of the 3 records get sent back
car,train,bike
boat,truck,plane
bike,plane,train

I would send them back the top 2 because the top one contains car and the second contains boat

View 5 Replies View Related

Storing Comma Seperated Values

Mar 7, 2008

Hi I have a text field called testing which shows the selection the user has made from a checked list. I want to save the contents of testing to a datadase with coloum varchar and with a comma to seperate the selections. It stores ok but sql queries do not recognise them as comma seperated values. e.g the selection from the vb code produses: Beauty, Fashion, Travel. Sql takes the lot as one. When I test a query say select from table type where Category = beauy it gives nothing. How do I store it so sql would recognise it as seperate enteries.
my vb code is below
Dim msg As StringDim li As ListItem
msg = ""For Each li In CaregoryCheckBoxList.Items
If li.Selected = True Then
'asp has a security default of no accetping html in input fields br is html code so causes error
'msg = msg & "<br>" & li.Text & " selected."
msg = msg & li.Text & "," & " "
End If
Next
Testing.Text = msg

View 10 Replies View Related

Script For Comma Seperated Values

Jul 23, 2005

To get rid of redundant data in a table, my cleint will be providingsomething like this:IDtokeep Ids to delete34 24,35,4912 14,178,145754 32,65,68I have to write a script for each of the above rows which looks likethis:-----------------------------------update sometableset id = 34where id in (24,35,49)delete from sometablewhere id in (24,35,49)-----------------------------------As I said I have to do this for EACH row. Can I somehow automate thisor will I need to write to same script for each row (there are about5000 rows in this audit table)Any help is highly appreciated.Here is the DDL and inserts for the audit table.IF object_id(N'dbo.dataclean','U') is not nullDROP TABLE [dbo].[dataclean]GOCREATE TABLE [dataclean] ([IdTokeep] int NULL ,[IdsTodelete] varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL )GOINSERT INTO [dataclean] ([IdTokeep],[IdsTodelete])VALUES(34,'24,35,49')INSERT INTO [dataclean] ([IdTokeep],[IdsTodelete])VALUES(12,'14,178,1457')INSERT INTO [dataclean] ([IdTokeep],[IdsTodelete])VALUES(54,'32,65,68')GO

View 3 Replies View Related

Passing Comma Seperated Parameter To SP

Jan 21, 2008

Hi,

My SP is,

ALTER PROCEDURE dbo.InventorySalesSummaryForReport(@ItemNumber nvarchar(30),@StoreId nvarchar(500),@Year int)

AS

DECLARE @SQL nvarchar(1000)

-- Searching ItemNumber in Inventory_SKU

DECLARE @Count int

DECLARE @ItemNumSKU varchar(50)

SET @SQL = N'SELECT @Count12 =COUNT(*) FROM Inventory WHERE Store_Id in (@StoreId1) AND ItemNum = @ItemNumber1'

EXECUTE sp_executesql @SQL,N'@Count12 int OUTPUT,@StoreId1 nvarchar(500),@ItemNumber1 nvarchar(30)',@Count12=@Count OUTPUT,@StoreId1 = @StoreId,@ItemNumber1 = @ItemNumber

IF (@Count = 0)

BEGIN

SET @SQL = N'SELECT @ItemNumSKU1 = ItemNum FROM Inventory_SKUS WHERE Store_Id in (@StoreId1) AND AltSKU = @ItemNumber1'

EXECUTE sp_executesql @SQL,N'@ItemNumSKU1 nvarchar(30) OUTPUT,@StoreId1 nvarchar(500),@ItemNumber1 nvarchar(30)',@StoreId1 = @StoreId,@ItemNumber1 = @ItemNumber,@ItemNumSKU1=@ItemNumSKU OUTPUT

SET @ItemNumber = @ItemNumSKU

END

-- Creating table variable to have values from 1 to 12

CREATE TABLE #MonthSales (MonthNumber int, MonthCost money,MonthPrice money,MonthQuan bigint)

DECLARE @Cnt INT

SET @Cnt = 1

WHILE(@Cnt <= 12)

BEGIN

INSERT INTO #MonthSales VALUES(@Cnt,0,0,0)

SET @Cnt = @Cnt + 1

END

--Joining query result with the table variable to get required result

DECLARE @Status1 Char(1)

SET @Status1 = 'C'

-- putting ' for comma seperated storeid

SET @SQL = N'SELECT'

SET @SQL = @SQL + N' MS.MonthNumber,'

SET @SQL = @SQL + N' ISNULL(Temp.MonthCost,0) MonthCost,'

SET @SQL = @SQL + N' ISNULL(Temp.MonthPrice,0) MonthPrice,'

SET @SQL = @SQL + N' ISNULL(Temp.MonthQuan,0) MonthQuan'

SET @SQL = @SQL + N' FROM'

SET @SQL = @SQL + N' (SELECT '

SET @SQL = @SQL + N' DATEPART(mm, DateTime) Month#'

SET @SQL = @SQL + N' ,SUM(CostPer*Quantity) As MonthCost'

SET @SQL = @SQL + N' ,SUM(PricePer*Quantity) AS MonthPrice'

SET @SQL = @SQL + N' ,SUM(Quantity) AS MonthQuan '

SET @SQL = @SQL + N' FROM '

SET @SQL = @SQL + N' Invoice_Totals '

SET @SQL = @SQL + N' INNER JOIN Invoice_Itemized ON Invoice_Totals.Invoice_Number = Invoice_Itemized.Invoice_Number '

SET @SQL = @SQL + N' WHERE '

SET @SQL = @SQL + N' Status = @Status AND Invoice_Totals.Store_ID in (@StoreId1) '

SET @SQL = @SQL + N' AND ItemNum = @ItemNumber1'

SET @SQL = @SQL + N' AND DATEPART(yy,datetime)=@Year1'

SET @SQL = @SQL + N' GROUP BY'

SET @SQL = @SQL + N' DATEPART(mm, DateTime)'

SET @SQL = @SQL + N' ) Temp '

SET @SQL = @SQL + N' RIGHT OUTER JOIN #MonthSales MS ON MS.MonthNumber = Temp.Month#'

SET @SQL = @SQL + N' ORDER BY MS.MonthNumber'

EXECUTE sp_executesql @SQL,N'@Status char(1),@StoreId1 nvarchar(500),@ItemNumber1 nvarchar(30),@Year1 int',@Status = @Status1,@StoreId1 = @StoreId,@ItemNumber1 = @ItemNumber,@Year1=@Year


It is working If I am passing sigle storeId to the above SP. If I am selecting multiple StoreIDs from the report. It is not returning correct value. Can you please give me a suggestion?

Thanks

View 3 Replies View Related

Select Many Records Into 1 Comma Seperated Field.

Oct 30, 2006

I want to pull out some information for documenting my user accounts.I want to be able to show all of the users and what companies those users have access to.

The table which stores the company information lists it in multiple rows, so there will be many results for each user
user -- companyid
johnd -- 2
johnd -- 5
johnd -- 1

I want to select this into one record so it will show up like this
user -- companies
johnd -- 2,5,1

The only way I know how to do this would be with a sub-query that uses a cursor to loop through & dump it into one string value, and then output the string value to the field. This seems extremely inefficient for such a seemingly simple task.

Can somebody help me out here?
thanks

View 3 Replies View Related

Comma Seperated Field To Arrays For Each Record?

May 12, 2008

Hello,

My SQL knowledge is limited so if I get stuff wrong then correct me... but I can imagine this task will be quite testing...

I am working on a system that logs ([Audit] table) the changes to fields on some tables using a Trigger on UPDATE. I need to produce a 'quick' report that returns the date when the tables overallStatus field was set to 1.

In the [Audit] table I can find all the field changes for the record in question using this SQL...

select *
from audit
where rowid = 1309606
order by auditID asc


My problem is filtering this data. The fields I need are formatted as below, see records returned, in ASC order...

audit.AuditID = 2652583
audit.OperationTime = 2008-04-24 15:12:07.740
audit.ColumnDetail = 'estimatedProductionPriceactualProductionCost'
audit.EditDetail = '0.00000.0000'


audit.AuditID = 2658460
audit.OperationTime = 2008-04-25 10:51:47.930
audit.ColumnDetail = 'overallStatusInsertionStatus'
audit.EditDetail = '05'



audit.AuditID = 2665723
audit.OperationTime = 2008-04-25 22:06:50.200
audit.ColumnDetail = 'overallStatusdespatchDateInsertionStatus'
audit.EditDetail = '1Â 3'



audit.AuditID = 2711092
audit.OperationTime = 2008-04-30 17:22:12.593
audit.ColumnDetail = 'overallStatusInsertionStatus'
audit.EditDetail = '34'



audit.AuditID = 2713217
audit.OperationTime = 2008-04-30 20:46:34.817
audit.ColumnDetail = 'clientOrderNumber'
audit.EditDetail = 'PAT12P7640'


The funny character, , is ASCII 127.


So need to find when 1309606's overallStatus was changed to 1. Manually looking at the data, I can see overallStatus was modified in 3 of the above 5 [Audit] records. It started life as 0, then went to 1 and then to 3. I'm aware that I need to look at the previous Audits date for when it was changed to the value I'm looking for... So it was changed to 1 on 2008-04-25 10:51:47.930.


What is the best way to approach this problem? I'm hoping to use T-SQL only and not have to use an external scripting language, unless I can embed vbscript or jscript inside a T-SQL function and then use arrays, etc?

Somehow I need to convert the ASCII(127) seperated list of fieldname into an array or list, find the index of the fieldname 'overallStatus' and then lookup that value in the datafield.


Hope that makes sense and any help would be great!


Cheers,
Nick

View 6 Replies View Related

How Do I Create An In-line Comma Seperated List

Jul 20, 2005

Scenario:Table 1 (a id, b name)Table 2 (a FKid, d value)A standard join on a gives me something like:a1 b1 d1a1 b1 d2What I want is:a1 b1 d1,d2I can easily do this with a function or cursor, but is is somewhatslow, and I need to do this a lot and I don't really want to have tomaintain tons of functions or cursors.Thoughts?

View 3 Replies View Related

Splitting A Column Into Multiple Columns?

Jun 10, 2014

I have to split a column using comma a delimiter into multiple columns. I am able to do it if i know how many column will be present in the final output. But in daily run, the columns may vary randomly.

how to split columns without hardcoding how many columns it ll come.

This is the code am using

Code:
WITH Split_Names (Fil_id,Name, xmlname)
AS
(
SELECT Fil_ID,

[Code].....

View 8 Replies View Related

Splitting 1 Column Into Multiple Columns

Apr 28, 2014

I have 1 column (memberassignment_1) that has the string in it - Port=A; Code=B; Sfx=C; Name=D; Night=E; Sig_Grp=F

I want to split this into 6 columns - Port, Code, sfx, Name, Night, Sig_Grp

EXAMPLE

PORT CODE SFX NAME NIGHT SIG_GRP
A B C D E F

View 11 Replies View Related

Help Splitting 1 Column Of Data Into Multiple

Apr 30, 2008



Hi

I have a table which has data "dumped" into it nightly and i need to create a "clean" table. Below are some sample rows:

1|name1|john|1234
2|name2|fred|2378
DS|address1|address2|postcode|telephoneno|area|propertytype


all the columns are separated with a "|" but the amount of columns are not fixed, so in lines 1 & 2 they are 4 columns and in line 3 there is 7 columns

thanks in advanced

Rich

View 4 Replies View Related

Need Sql To Return The Result Of A Query As Comma Seperated Values.

Jun 28, 2005

Hi,   I need a sql that returns the query result as comma seperated list of values, instead of several rows. Below is the scenario...   Table Name - Customer   Columns - CustomerID, Join DateSay below is the data of Customer table ...CustomerID    JoinDate1                   04/01/20052                   01/03/20033                   06/02/20044                   01/05/20025                   09/07/2005Now i want to retrieve all the customerid's who have joined this year. Below is the query that i use for this case.Select CustomerID from Customer where JoinDate between '01/01/2005' and GetDate()This gives the below result as two rows.CustomerID15But i need to get the result as '1,5' (comma seperated list of resulting values).Any help is highly appreciatedThanks in AdvanceRamesh

View 4 Replies View Related

Inserting From A Comma-seperated Ascii-file With Logics

Nov 17, 1999

Hi all !

I want to insert things to SQL-server from an ascii file but I also want to add logics with IF - Then _ Else statements. I guess the only way is to make a
stored Procedure.

How do you do when you want to read from a text file using the data into variables and then write it into the database ?

View 2 Replies View Related

Get All The Matching Values In ColB And Display It Against ColA As Comma Seperated In The Same Row

Nov 6, 2007



Hi all sql gurus,

I have a table that has product name and submissionID and some other columns. I am really concerned about these two columns. My task is to get all the submissionIDs for a particular product name and display SubmissionIDs seperated by commas against each product name .
The tables below might give a better idea
current scenario:
Product Name SubmissionID columnC Column D
AAA 123
AAA 456
BBB 111
ccc 121
AAA 789
Expected result:
Product Name SubmissionID columnC Column D
AAA 123,456,789
BBB 111
CCC 121
Any suggestions/pointers would be highly appreciated.

View 5 Replies View Related

Multiple Rows Into A Comma Delimited String

May 22, 2007

I have the following table:id name1 yes2 no3 what4 is5 this6 niceThe amount of rows can vary from 1 to 50. I only need the name column.What SQL statement do I have to execute to get the following:yes,no,what,is,this,nice,  (trailing , is acceptable)Thanks!

View 1 Replies View Related

How To Insert Results Of A SQL Query Into The Field Of Another Table, As Comma Seperated Values.

Mar 7, 2008



I am currently working on an application that requires, insertion of the results of a SQL Query in to the field of another table, in the form of a comma separated values.

For example, to explain things in detail:

create table dbo.phone_details

(country varchar(20),
state varchar(30),
list_of_toll_free_numbers text)


insert into dbo,phone_details
values
( 'USA', 'CA', 'select Phone from phone_table where substring(phone, 1, 3) in ('800', '866', '877', '888')' )

The final output I desire is:

country state list_of_toll_free_numbers

---------- ------- -----------------------------------------
USA CA 8009877654, 8665764398, 8776543219

View 8 Replies View Related

How To Select Multiple Rows As Comma Separated List?

Jul 4, 2004

Hi,

I have a table of users, a table of categories, and a many-to-many table linking users to categories.

My problem is that I want to select all the users with an extra column containing a comma-separated list of the categories they belong to.

Here is a stripped-down version of the table fields:

tbl_User
UserId, Email

tbl_Category
CatId, CatName

tbl_User_Category
UserId, CatId


I have tried using the coalesce function to build a string, but can only get this to work for one row at a time:

DECLARE @list nvarchar(100)

SELECT @list = COALESCE(@list + ', ', '') + CAST(CatId AS varchar(4))
FROM tbl_User_Category
WHERE UserId = @UserId

SELECT @list as List


Any ideas on how to add to this to get it to do each row in tbl_Page? Or am I attacking this from the wrong angle?????

Any help would be fantastic!

thanks,
Rob

View 4 Replies View Related

Insert Into Multiple Rows Instead Of One Comma-delimited List?

Jul 20, 2005

Hi, all:I have a form which lets users choose more than one value for each question.But how do I insert each value as a separate row in my table (instead ofhaving the values submitted as a comma-delimited list)?Thanks for your help.J

View 2 Replies View Related

SQL Server 2012 :: Splitting A Single Column Into Multiple Columns?

Mar 3, 2015

I have a description field in a table which also stores unit of measure in the same column but with some space between them, I need to split these into two different columns.

For Eg:

Description
APPEARANCE UNIT
BDV KV
DENSITY KG/L

View 9 Replies View Related

SQL Server 2008 :: How To Select Multiple Rows Delimited With Comma

Oct 6, 2015

I have a table like this :

ID Description ParentID Level
B.01 Parent 1 H
B.01.01 Parent 1.1 B.01 H
B.01.01.01 Parent 1.1.1 B.01.01 H
B.01.01.01.01 Detail 1 B.01.01.01 D
B.01.01.01.02 Detail 2 B.01.01.01 D

[Code] .....

That means, only select Level=H, and display the last record of H with concatenated the description of each rows delimited with comma.

View 2 Replies View Related

SQL Server 2012 :: Splitting Column Values In Multiple Columns And Assigning It To Row

Dec 11, 2013

How do I write a query using the split function for the following requirement.I have a table in the following way

Identity Name Col1 Col2 Col3
1 Test1 1,2,3 200,300,400 3,4,6
2 Test2 3,4,5 300,455,600 2,3,8

I want an output in the following format

Identity Name Col1 Col2 Col3
1 Test1 1 200 3
1 Test1 2 300 4
1 Test1 3 400 6
2 Test2 3 300 2
2 Test2 4 455 3
2 Test2 5 600 8

If you see the data, first element in col1 is matched to first element in col2 and 3 after splitting the string.

View 2 Replies View Related

Transact SQL :: Keep Entire Columns Into 2 Rows When There Is A Comma In A Column

Nov 2, 2015

I have a table and one of the column have tab delimited value and I need to separate the tab delimited values and keep them in separate rows.

ID       Name                  State      Country
1       Scott, Ricky            NSW       AUS
2       Martin                   VIC         AUS
3    James, Peter,John     WA        AUS

ID column is not a primary key. I want the output columns to identify the comma (,) and put them in separate rows as below

ID       Name                  State      Country
1       Scott                     NSW       AUS
1       Ricky                     NSW       AUS
2       Martin                   VIC         AUS
3      James                     WA        AUS
3      Peter                      WA        AUS
3      John                       WA        AUS

How to strip the camma(,) in SQL?

View 3 Replies View Related

How Do I Return All Rows Value In A Single Column Delimit With Comma Separation?

Oct 23, 2007

Dear all,

I have a table like:

State -- Customer
TN -- AAA
TN -- AAA1
TN -- AAA2
Delhi -- BBB
Delhi -- BBB1
Delhi -- BBB2
Mumbai -- CCC
Mumbai -- CCC1
Mumbai -- CCC2
Maharashtra -- DDD
Maharashtra -- DDD1
Maharashtra -- DDD2

I want to show the output in a single query like:

State -- Customers
TN -- AAA, AAA1, AAA2
Delhi -- BBB, BBB1, BBB2
Mumbai -- CCC, CCC1, CCC2
Maharastra -- DDD, DDD1, DDD2


How do i do this in a single query

Can Pivot query will help in this situation. Please explain with a sample query

Thanks
gopalan@sofist.com
okugops@hotmail.com

View 4 Replies View Related

Splitting A Comma Delimited String

Oct 1, 2007

I have a string like say: '3:4:5:4,2:4:1,4:1:2:5:2'. Now I need to split the substrings delimited by commas. So my final output shall be

3:4:5:4
2:4:1
4:1:2:5:2


I did write a piece of code to achieve the same, but I feel its not so efficient. Can anyone suggest me a better way, if any? My code is as follows:

Declare @person as varchar(255), @cnt smallint,@loc smallint,@prevloc smallint, @str varchar(255)
Select @prevloc=0,@loc=1,@cnt=1,@person = '3:4:5:4,2:4:1,4:1:2:5:2'
While @loc != 0
begin
set @prevloc=(case when @loc = 1 then 0 else @loc end) +1
set @loc = charindex(',',@person,@loc+1)
Set @str = substring(@person,@prevloc,(Case when @loc = 0 then len(@person) - @prevloc + 1 else @loc - @prevloc end))
print 'String = ' + @Str
set @cnt=@cnt+1
end

RESULT
------
String = 3:4:5:4
String = 2:4:1
String = 4:1:2:5:2


Note: My actual purpose is to also sub split it again with ':' delimiter too. So looking for an efficient code.

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved