Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Sunday, March 25, 2012

converting a text field to number

I have a table with over a million rows and one of the fields contains
amounts of money in text format.
What is the most efficient way of converting this field to a number
format that I can sum on?

Regards,
CiarnHi Ciaran,

Before converting the type of the col, make sure that there are no
invalid values in that column. You can pull them out by

SELECT colName FROM tabName WHERE IsNumeric(colName) = 0

Alter your column type by

ALTER TABLE tableName ALTER COLUMN colName NUMERIC

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Nazeer Oasis (nazeerpp@.indiatimes.com) writes:
> Before converting the type of the col, make sure that there are no
> invalid values in that column. You can pull them out by
> SELECT colName FROM tabName WHERE IsNumeric(colName) = 0
> Alter your column type by
> ALTER TABLE tableName ALTER COLUMN colName NUMERIC

Unfortunately, this may still fail, since IsNumeric will approve of
values than converts to float or money, but not to numeric. Also, I
say that it's extremely bad practice to say numeric without specifying
scale and precision. You get some defaults, but these may not be what
you expect.

As for the original query, the easy way is:

SELECT SUM(convert(int, textcol)) FROM tbl
or SELECT SUM(convert(money, textcol)) FROM tbl

But this will of course fail if there are strings that does not convert.

If all data is integer, that is the text is undelimited and there are
no decimals, then it's pretty easy to test:

textcol NOT LIKE '%[0-9]%'

If the text can delimiters and decimals, it can become quite hairy
to filter.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Erland Sommarskog (esquel@.sommarskog.se) writes:
> If all data is integer, that is the text is undelimited and there are
> no decimals, then it's pretty easy to test:
> textcol NOT LIKE '%[0-9]%'

This is wrong. I forgot a ^:

textcol NOT LIKE '%[^0-9]%'

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Sunday, March 11, 2012

convert the rows into column

I want to convert the row value as column name

example:-->

value ratio

3 4.16666666666
1 1.31578947368
0 0
0 0

To :->

value ratio ratio1 ratio2 ratio3

3 4.166 1.315 0 0

any ideas?

If you are running sql server 2005 you can do it with a pivot table. If sql 2000, I think you have to code it yourself. See

http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm

http://www.sqlservercentral.com/articles/Advanced+Querying/pivottableformicrosoftsqlserver/2434/ (registration required)

http://sqlserver2000.databases.aspfaq.com/how-do-i-create-a-cross-tab-or-pivot-query.html

Wednesday, March 7, 2012

Convert rows to delimited string

Does RS have any function that would enable me to convert multiple
rows into a comma-delimited string? My report is very long due to multiple
instances of a child record that is represented by a single word. If I could
append
the column values it would significantly compress the report.
Example where the tables are Cust and Order and joined on Order.CustId:
Change from this:
CustId CustName OrderColors
-- -- --
100 Anderson Red
100 Anderson Green
100 Anderson Yellow
To this:
CustId CustName OrderColors
-- -- --
100 Anderson Red, Green, YellowRS doesn't have such a function. I would do this at the data source. If you
use SQL Server 2005, if I am not wrong, there is a custom aggregate sample
that does exactly this.
--
HTH,
---
Teo Lachev, MVP, MCSD, MCT
"Microsoft Reporting Services in Action"
"Applied Microsoft Analysis Services 2005"
Home page and blog: http://www.prologika.com/
---
"Mike Harbinger" <MikeH@.Cybervillage.net> wrote in message
news:OOFXEMS9FHA.3492@.TK2MSFTNGP10.phx.gbl...
> Does RS have any function that would enable me to convert multiple
> rows into a comma-delimited string? My report is very long due to multiple
> instances of a child record that is represented by a single word. If I
> could append
> the column values it would significantly compress the report.
> Example where the tables are Cust and Order and joined on Order.CustId:
> Change from this:
> CustId CustName OrderColors
> -- -- --
> 100 Anderson Red
> 100 Anderson Green
> 100 Anderson Yellow
> To this:
> CustId CustName OrderColors
> -- -- --
> 100 Anderson Red, Green, Yellow
>
>

Convert rows to colums

I am getting this from my client
TableA
StorID LineNumber Text
30000 1 ClientName
30000 2 ClientSurname
30000 3 3333333
30000 4 20-05-2004

I actually want this to look like
TableB
StoryID Name Surname Policy Date
30000 Name Surname 3333333 20-05-2004

Can you help with the script to convert this to one record with many fields (as in TableB) if this isyou need a sort of a pivot table where the cross function is the identity function. I've used this code in a project, and it works fine,..though performance are surely not the best. Otherwise you can wait for SQL2005 :-)

some very useful code (very general, you probably should modify it to best suit your db schema) can be found here:

http://www.sqlteam.com/item.asp?ItemID=2955|||create a function (called get_val) with storid, and linenumber as arguements.

in the function:

select <text> from tableA
where storid = <arg1> and linenumber = <arg2>
return <text>

then...to populate table b:

INSERT INTO tableB (storid,name,surname,policy_date)
SELECT DISTINCT storid, get_val(storid,1),get_val(storid,2),get_val(storid ,3),get_val(storid,4) FROM tableA|||I'd suggest using something like:SELECT a.storID
, Min(CASE WHEN 1 = a.LineNumber THEN a.[Text]) AS [Name]
, Min(CASE WHEN 2 = a.LineNumber THEN a.[Text]) AS [Surname]
, Min(CASE WHEN 3 = a.LineNumber THEN a.[Text]) AS [Policy]
, Min(CASE WHEN 4 = a.LineNumber THEN a.[Text]) AS [Date]
FROM TableA AS a
GROUP BY a.StorID-PatP|||much better....nice pat.

convert rows to columns

I hope I am able to explain you my situation
I have a table called levelAllocation. A snapshot of the table looks as
follows
LAID LVID ALID PERCENT
1 1 4 10
2 1 5 20
3 1 6 30
4 2 4 45
5 2 5 55
6 2 6 65
I want a stored procedure that would output following
LAID LVID ALID4 ALID5 ALID6 PERCENT
1 1 4 NULL NULL 10
2 1 NULL 5 NULL 20
3 1 NULL NULL 6 30
4 2 4 NULL NULL 45
5 2 NULL 5 NULL 55
6 2 NULL NULL 6 65
Any other suggestion will be welcomed.
Regards,
A
Try this:
(edit with your table name)
select t1.LAID
, t1.LVID
, t2.ALID4
, t2.ALID5
, t2.ALID6
, t1.[Percent]
from [table_name] t1
inner join (
select LAID
, (case ALID when 4 then ALID else NULL end) AS ALID4
, (case ALID when 5 then ALID else NULL end) AS ALID5
, (case ALID when 6 then ALID else NULL end) AS ALID6
from [table_name]
group by LAID, ALID
) t2
on t1.LAID = t2.laid
"Ashutosh" wrote:

> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A
>
|||Yes , you can search for pivot tables, that is what i think you're
looking for.
Ashutosh wrote:
> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A
|||Check out RAC.
www.rac4sql.net

convert rows to columns

Hi All,

I have two tables

TblEmployee

EmpID,

EmpName

TblAddress

AddressID

EmpID

Address1

Address2

AddressType (will hold values like ‘TP’, ‘HP’ storing different address types)

If I do a simple join assuming 2 different address types exists for each employee. I would be getting two rows. But I need address1 and address2 of different address types as four columns I mean address1 of type ‘TP’, address2 of type ‘TP’, address1 of type ‘HP’, address2 of type ‘HP’

along with employee information.

Can some body help me with the query.select *
from TblEmployee e
inner join (
select EmpID,
TP_Address1 = max(case when AddressType = 'TP' then Address1 end),
TP_Address2 = max(case when AddressType = 'TP' then Address2 end),

HP_Address1 = max(case when AddressType = 'HP' then Address1 end),

HP_Address2 = max(case when AddressType = 'HP' then Address2 end)
from TblAddress
group by EmpID
) a
on e.EmpID = a.EmpID|||Thanks a lot K H Tan

convert rows to columns

I hope I am able to explain you my situation
I have a table called levelAllocation. A snapshot of the table looks as
follows
LAID LVID ALID PERCENT
1 1 4 10
2 1 5 20
3 1 6 30
4 2 4 45
5 2 5 55
6 2 6 65
I want a stored procedure that would output following
LAID LVID ALID4 ALID5 ALID6 PERCENT
1 1 4 NULL NULL 10
2 1 NULL 5 NULL 20
3 1 NULL NULL 6 30
4 2 4 NULL NULL 45
5 2 NULL 5 NULL 55
6 2 NULL NULL 6 65
Any other suggestion will be welcomed.
Regards,
ATry this:
(edit with your table name)
select t1.LAID
, t1.LVID
, t2.ALID4
, t2.ALID5
, t2.ALID6
, t1.[Percent]
from [table_name] t1
inner join (
select LAID
, (case ALID when 4 then ALID else NULL end) AS ALID4
, (case ALID when 5 then ALID else NULL end) AS ALID5
, (case ALID when 6 then ALID else NULL end) AS ALID6
from [table_name]
group by LAID, ALID
) t2
on t1.LAID = t2.laid
"Ashutosh" wrote:
> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A
>|||Yes , you can search for pivot tables, that is what i think you're
looking for.
Ashutosh wrote:
> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A|||Check out RAC.
www.rac4sql.net

convert rows to columns

I hope I am able to explain you my situation
I have a table called levelAllocation. A snapshot of the table looks as
follows
LAID LVID ALID PERCENT
1 1 4 10
2 1 5 20
3 1 6 30
4 2 4 45
5 2 5 55
6 2 6 65
I want a stored procedure that would output following
LAID LVID ALID4 ALID5 ALID6 PERCENT
1 1 4 NULL NULL 10
2 1 NULL 5 NULL 20
3 1 NULL NULL 6 30
4 2 4 NULL NULL 45
5 2 NULL 5 NULL 55
6 2 NULL NULL 6 65
Any other suggestion will be welcomed.
Regards,
ATry this:
(edit with your table name)
select t1.LAID
, t1.LVID
, t2.ALID4
, t2.ALID5
, t2.ALID6
, t1.[Percent]
from [table_name] t1
inner join (
select LAID
, (case ALID when 4 then ALID else NULL end) AS ALID4
, (case ALID when 5 then ALID else NULL end) AS ALID5
, (case ALID when 6 then ALID else NULL end) AS ALID6
from [table_name]
group by LAID, ALID
) t2
on t1.LAID = t2.laid
"Ashutosh" wrote:

> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A
>|||Yes , you can search for pivot tables, that is what i think you're
looking for.
Ashutosh wrote:
> I hope I am able to explain you my situation
> I have a table called levelAllocation. A snapshot of the table looks as
> follows
> LAID LVID ALID PERCENT
> 1 1 4 10
> 2 1 5 20
> 3 1 6 30
> 4 2 4 45
> 5 2 5 55
> 6 2 6 65
> I want a stored procedure that would output following
> LAID LVID ALID4 ALID5 ALID6 PERCENT
> 1 1 4 NULL NULL 10
> 2 1 NULL 5 NULL 20
> 3 1 NULL NULL 6 30
> 4 2 4 NULL NULL 45
> 5 2 NULL 5 NULL 55
> 6 2 NULL NULL 6 65
> Any other suggestion will be welcomed.
> Regards,
> A|||Check out RAC.
www.rac4sql.net

Convert Rows to Columns

Hi All,

I need to help with converting rows to columns in SQL2k.

Input:
Id Name Role

58Ron Doe Associate
58Mark BonasDoctor
59Mike JohnsonDoctor
59John SmithAssociate
102Chris CarterAssociate
102Ron Doe Associate
102James JonesAssociate

Output should look like:

IdDoctorAssoc1Assoc2Assoc3

58Mark BonasRon Doe NULLNULL
59Mike JohnsonJohn SmithNULLNULL
102NULLChris CarterRon Doe James Jones

There could be more than 3 associates in the input but I only need 3
above columns for associates.

I used following query:
SELECT Q.sales_id,
doctor2= (SELECT Q2.name FROM view1 Q2 where Q2.role = 'doctor'
and Q2.sales_id = Q.sales_id),
assoc1= (SELECT Q2.name FROM view1 Q2 where Q2.role =
'associate' and Q2.sales_id = Q.sales_id),
assoc2= (SELECT Q2.name FROM view1 Q2 where Q2.role =
'associate' and Q2.sales_id = Q.sales_id),
assoc3= (SELECT Q2.name FROM view1 Q2 where Q2.role =
'associate' and Q2.sales_id = Q.sales_id)
FROM view1 Q
GROUP BY sales_id

and I get this error "Subquery returned more than 1 value" since there
are multiple associate for Id 102.

Thenks<ambersaria420@.yahoo.com> wrote in message
news:1106185678.994241.297820@.c13g2000cwb.googlegr oups.com...
> Hi All,
> I need to help with converting rows to columns in SQL2k.
> Input:
> Id Name Role
> 58 Ron Doe Associate
> 58 Mark Bonas Doctor
> 59 Mike Johnson Doctor
> 59 John Smith Associate
> 102 Chris Carter Associate
> 102 Ron Doe Associate
> 102 James Jones Associate
>
> Output should look like:
> Id Doctor Assoc1 Assoc2 Assoc3
> 58 Mark Bonas Ron Doe NULL NULL
> 59 Mike Johnson John Smith NULL NULL
> 102 NULL Chris Carter Ron Doe James Jones
>
> There could be more than 3 associates in the input but I only need 3
> above columns for associates.
> I used following query:
> SELECT Q.sales_id,
> doctor2= (SELECT Q2.name FROM view1 Q2 where Q2.role = 'doctor'
> and Q2.sales_id = Q.sales_id),
> assoc1= (SELECT Q2.name FROM view1 Q2 where Q2.role =
> 'associate' and Q2.sales_id = Q.sales_id),
> assoc2= (SELECT Q2.name FROM view1 Q2 where Q2.role =
> 'associate' and Q2.sales_id = Q.sales_id),
> assoc3= (SELECT Q2.name FROM view1 Q2 where Q2.role =
> 'associate' and Q2.sales_id = Q.sales_id)
> FROM view1 Q
> GROUP BY sales_id
> and I get this error "Subquery returned more than 1 value" since there
> are multiple associate for Id 102.
> Thenks

This is very awkward to write in TSQL, especially since the number of
associates may vary - you would need a cursor (maybe even nested cursors) to
loop through the table for each ID. A better solution is to do this in the
front end or using a reporting tool.

Simon|||I changed the query to following:

select distinct v1.sales_id, v1.name as doctor2 , v2.name as assoc1,
v3.name as assoc2, v4.name as assoc3

from

(select sales_id, max(case when role = 'Doctor' then name else NULL
end) as name from view1

group by sales_id) v1

left join (select sales_id , name from view1 where role = 'Associate'
) v2 on v1.sales_id = v2.sales_id

left join (select sales_id , name from view1 where role = 'Associate'
) v3 on v1.sales_id = v3.sales_id and (v3.name is null or v3.name >
v2.name)

left join (select sales_id , name from view1 where role = 'Associate'
) v4 on v1.sales_id = v4.sales_id and (v4.name is null or( v4.name >
v2.name and v4.name > v3.name))

However now it return extra row if there is more than one associate.

New Output:

58Mark BonasRon Doe NULL NULL
59Mike Johnsonjohn2 smithNULL NULL
102NULL Chris CarterJames JonesRon Doe
102NULL Chris CarterRon Doe NULL
102NULL James JonesRon Doe NULL
102NULL Ron Doe NULL
NULL

Thanks Again.|||It's ugly to write this in SQL. If you really want to do this, you can
do it using temp tables.
-------------------------------------

create table #T
(i int, name varchar(50), role varchar(50))

insert #T
values('58','Ron Doe','Associate')
insert #T
values('58','Mark Bonas','Doctor')
insert #T
values('59','Mike Johnson','Doctor')
insert #T
values('59','John Smith','Associate')
insert #T
values('102','Chris Carter','Associate')
insert #T
values('102','Ron Doe','Associate')
insert #T
values('102','James Jones','Associate')

-- doctor and first associate
select
i,
min(case when role='doctor' then name else 'zzz' end) as doctor,
min(case when role='associate' then name else 'zzz' end) as
associate
into #T1
from #T
group by i

-- second associate
select
#T.i,
min(case when role='associate' then name else 'zzz' end) as
associate
into #T2
from #T
left join #T1 on #T.i=#T1.i and #T.name=#T1.associate
where #T1.associate is null
group by #T.i

-- third associate
select
#T.i,
min(case when role='associate' then name else 'zzz' end) as
associate
into #T3
from #T
left join #T1 on #T.i=#T1.i and #T.name=#T1.associate
left join #T2 on #T.i=#T2.i and #T.name=#T2.associate
where #T1.associate is null and #T2.associate is null
group by #T.i

-- output
select #T1.i, #T1.doctor, #T1.associate as assoc1, #T2.associate as
assoc2, #T3.associate as assoc3
from #T1
join #T2 on #T1.i=#T2.i
join #T3 on #T1.i=#T3.i

Convert Rows into Columns... (Cross tab).

Hi genius,

I got the result set as shown below (By executing another query i got this).

Month Status Count
===== ====== =====
April I 129
April O 4689
April S 6
July I 131
July O 4838
July S 8
June I 131
June O 4837
June S 8
May I 131
May O 4761
May S 7

But, I need the same result set as below


Month I O S
===== = = =
April 129 4689 6
July 131 4838 8
June 131 4837 8
May 131 4761 7

Can anyone provide me the tips/solution.

Thanks in advance

Regards,
j_jst

You can try "Pivot transformation". Book online has examples.|||

You can also select the cells, copy, shift F10, select paste and transpose. The selected rows will copy in columnar form.

Good Luck

|||

Hi,

I also have a same problem. Can you suggest what was your solution?

regards

Josh

|||

I also need to do something similar...

It was suggested that I would probably need to use a cursor in a stored procedure which loops through the rows and updates a temporary table with the values I need.

I haven’t got round to doing this yet… so if anybody has a solution which I could have a look at I’d be very grateful.

I’ll post my solution when I’ve got it.

|||

Jon:

What version of SQL Server are you using? Also, a cursor is NOT normally a good idea. Take a look at some of these posts:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1372104&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=892822&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=447559&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=437891&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=588762&SiteID=1

Please open a new thread and post what you are trying to accomplish.

|||

select [Month],
max(case when [Status]='I' then [Count] end) as I,
max(case when [Status]='O' then [Count] end) as O,
max(case when [Status]='S' then [Count] end) as S
from mytable
group by [Month]
order by [Month]

|||Mark's response is why I want you to post a new thread. Sorry, Mark. Should I split this thread?|||

Thanks for the links kent.

I have managed to solve my problem.

Convert Rows into Columns... (Cross tab).

Hi genius,

I got the result set as shown below (By executing another query i got this).

Month Status Count
===== ====== =====
April I 129
April O 4689
April S 6
July I 131
July O 4838
July S 8
June I 131
June O 4837
June S 8
May I 131
May O 4761
May S 7

But, I need the same result set as below


Month I O S
===== = = =
April 129 4689 6
July 131 4838 8
June 131 4837 8
May 131 4761 7

Can anyone provide me the tips/solution.

Thanks in advance

Regards,
j_jst

You can try "Pivot transformation". Book online has examples.|||

You can also select the cells, copy, shift F10, select paste and transpose. The selected rows will copy in columnar form.

Good Luck

|||

Hi,

I also have a same problem. Can you suggest what was your solution?

regards

Josh

|||

I also need to do something similar...

It was suggested that I would probably need to use a cursor in a stored procedure which loops through the rows and updates a temporary table with the values I need.

I haven’t got round to doing this yet… so if anybody has a solution which I could have a look at I’d be very grateful.

I’ll post my solution when I’ve got it.

|||

Jon:

What version of SQL Server are you using? Also, a cursor is NOT normally a good idea. Take a look at some of these posts:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1372104&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=892822&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=447559&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=437891&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=588762&SiteID=1

Please open a new thread and post what you are trying to accomplish.

|||

select [Month],
max(case when [Status]='I' then [Count] end) as I,
max(case when [Status]='O' then [Count] end) as O,
max(case when [Status]='S' then [Count] end) as S
from mytable
group by [Month]
order by [Month]

|||Mark's response is why I want you to post a new thread. Sorry, Mark. Should I split this thread?|||

Thanks for the links kent.

I have managed to solve my problem.

Convert Rows into Columns... (Cross tab).

Hi genius,

I got the result set as shown below (By executing another query i got this).

Month Status Count
===== ====== =====
April I 129
April O 4689
April S 6
July I 131
July O 4838
July S 8
June I 131
June O 4837
June S 8
May I 131
May O 4761
May S 7

But, I need the same result set as below


Month I O S
===== = = =
April 129 4689 6
July 131 4838 8
June 131 4837 8
May 131 4761 7

Can anyone provide me the tips/solution.

Thanks in advance

Regards,
j_jst

You can try "Pivot transformation". Book online has examples.|||

You can also select the cells, copy, shift F10, select paste and transpose. The selected rows will copy in columnar form.

Good Luck

|||

Hi,

I also have a same problem. Can you suggest what was your solution?

regards

Josh

|||

I also need to do something similar...

It was suggested that I would probably need to use a cursor in a stored procedure which loops through the rows and updates a temporary table with the values I need.

I haven’t got round to doing this yet… so if anybody has a solution which I could have a look at I’d be very grateful.

I’ll post my solution when I’ve got it.

|||

Jon:

What version of SQL Server are you using? Also, a cursor is NOT normally a good idea. Take a look at some of these posts:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1372104&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=892822&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=447559&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=437891&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=588762&SiteID=1

Please open a new thread and post what you are trying to accomplish.

|||

select [Month],
max(case when [Status]='I' then [Count] end) as I,
max(case when [Status]='O' then [Count] end) as O,
max(case when [Status]='S' then [Count] end) as S
from mytable
group by [Month]
order by [Month]

|||Mark's response is why I want you to post a new thread. Sorry, Mark. Should I split this thread?|||

Thanks for the links kent.

I have managed to solve my problem.

convert rows into columns

i have a table which gives me a list of months as records...
ie..columnname : month
row1: jan
row2: feb
row 3: mar
and so on..
i want to make a column..where these months appear as column name
ie...column1: jan
column2: feb
column3: mar
also...what i want is if in the first table...any month is added as a row... the second table should also take the new month as a new column...
let me know asap
regards
Nikhil
MSKB (support.microsoft.com) article : 175574
Anith

Friday, February 24, 2012

Convert Ntext type to XML type

I have a ntext column which stores rows of xml data.

Ive decided that the best way to query the xml data is to Convert the ntext data into xml data type and use Sql Server 2005 builtin Xml Query tools to perform FLWOR expressions. The problem Im having is getting the ntext data Converted to xml.

When I try to convert the ntext text, I of course get an error that local variables of ntext type are invalid.

Any suggestions on a way I might accomplish this?

Thanks, -lance

Hi,

From your description, it seems that you met trouble while you are going convert the field type from ntext to xml, right?

Based on my understanding , there are several factors which may cause the failure of the converting. Please make sure that you are not using "UTF-8" for your XML encoding in your ntext field. You can use "UTF-16" instead.

Another factor is you should make sure that the XML schema is right and the tags are in the right format, otherwise, it would also cause the failure of the converting.

Thanks.

Convert month name, year range to mm/dd/yy

Using SQL 2000. I need to select rows based on a date range. Both the
beginning date and ending date of the range will be entered in the
mm/dd/yy format. There are 2 columns in the table called MonthOfEval
and YearOfEval, both varchar(9) and both with data like "August" and
"2005-2006". I think I need to use these 2 columns to create a date in
the mm/dd/yy format, then use that newly created date to see if it's
within the date range. How would I go about doing this or is there a
better way?

Thanks for any help or advice.(manning_news@.hotmail.com) writes:
> Using SQL 2000. I need to select rows based on a date range. Both the
> beginning date and ending date of the range will be entered in the
> mm/dd/yy format. There are 2 columns in the table called MonthOfEval
> and YearOfEval, both varchar(9) and both with data like "August" and
> "2005-2006". I think I need to use these 2 columns to create a date in
> the mm/dd/yy format, then use that newly created date to see if it's
> within the date range. How would I go about doing this or is there a
> better way?

First of all, when you are in SQL Server you should work with dates
in the datetime datatype, which is a binary container. When you pass
dates to SQL Server, you use parameterised commands or stored procedures.
You pass the client API the date as a string, and the API interprets it
according to regional settings.

If you need to manipulate dates as strings in SQL Server, use the format
YYYYMMDD, as this format is not subject to different interpretations
depending on settings.

Next, it is not clear what "2005-2006" and "August" would mean. The first
I could interpret as 2005-01-01 to 2006-12-31. A single month name is
more tricky. OK, from 08-01 to 08-31, but which year? Any of 2005 and
2006? Or is here some broken fiscal year involved, so that 2005-2006
means 2005-07-01 to 2006-06-30?

The general advice for this sort of question is to post:

o CREATE TABLE (preferrably simplified) for your table.
o INSERT statements with sample data.
o The desired result given the sample.

This has both the effect of clarifying what you are asking for, and to
make it easy to develop a tested solution.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Sunday, February 19, 2012

Convert int to float

Hi,
why does converting integer to float take so long? Its a column with about 5 Million rows.
I want to avoid cast(inumber1 as float) / cast(inmuber2 as float), thats why converting them. Queries should be a bit faster after that.. hope so :)
Thanks a lotWhat method are you using to convert?
How long is so long?

Your last sentence doesn't make a lot of sense - if you're converting datatypes during your select statements that's adding processing time to your query, so surely it will not make them faster.

In fact, please post the SQL statement in question as well :)|||First of all, converting anything to float is a "computationally noisy" operation... It means a lot of work for the CPU no matter how you do it, just because of how the FLOAT datatype is stored.

My preference for doing what you've described is peculiar, but it works well for me... I would try using:SELECT 1e0 * inumber1 / inmuber2-PatP|||Thanks a lot Pat, that's a nice trick!|||What method are you using to convert?
How long is so long?

It was Alter Table A Alter Column C float NOT NULL and took about 20 Minutes.

if you're converting datatypes during your select statements that's adding processing time to your query, so surely it will not make them faster.

That's why I did the Alter Command. I just wondered why its such a big thing from int to float|||for very large tables, it probably would be faster to export the table to a flat file using bcp, then reimport to a different table with the new datatype, again with bcp.

I tend to shy away from ALTER TABLE.|||As I see it, there is three main reasons for this operation to take take quite a bit of time:

First, creating the float value requires processing power. However, this does not explain how updating a table with 5M records takes so long.

Second, A float takes 8 bytes, whereas int takes 4 bytes. So, depending on the width of the table, you may experience page splits (There is no longer room for all the rows in the page, so some rows have to be moved to a new page). I'm pretty sure this will be especially bad if there is a clustered index on the table.

And last, if this is done in an active environment, keep in mind that you'll require exclusive schema lock on the table, so your command will have to wait until a point in time when there is no activity against the table.

So, finally... I don't think queries will run any faster. You'll probably end up having more data pages, and I'm pretty sure that the negative impact from this is of greater magnitude than the cast from int to float.|||Wow, that was a really detailed comment :-) thank you

As I already have converted, does it make any sense to reconvert to integer regarding the negative impact of greater magnitude?|||int to float

What the hell for?

There's no precision in int. Are you looking for precision? Then use decimal.

Let me ask...does anyone use float or real, and if so what for?

I gotta do a poll|||Have you ever divided two integer values?|||int to float

What the hell for?

There's no precision in int. Are you looking for precision? Then use decimal.

Let me ask...does anyone use float or real, and if so what for?

I gotta do a pollI think you mean "There's no precision in float". And a float is more precise when you do complex math (the sort of complex I don't really understand frankly). Michael Valentine Jones did a good proof on SQLTeam. I'm sure Pat could explain too. I've got a link to a page that goes into this in depth but have never had chance to read it yet.
EDIT - linky: http://docs.sun.com/source/806-3568/ncg_goldberg.html

Anyway - you are right though - for most purpses you would prefer decimal over floats.|||Have you ever divided two integer values?You get an integer return unless you explicitly cast or do what Pat did. Did you seriously get a performance improvement starting off with floats?|||Correct me, if I'm wrong, but float takes less space than decimal, doesn't it?|||You get an integer return unless you explicitly cast or do what Pat did. Did you seriously get a performance improvement starting off with floats?
Not really, but 5M rows is still pretty small. Frankly, I thought one of you could give me that answer ;-)|||BOL

float and real
Approximate number data types for use with floating point numeric data. Floating point data is approximate; not all values in the data type range can be precisely represented.

Decimal

Precision Storage bytes
1 - 9 5
10-19 9
20-28 13
29-38 17

bigint

Integer (whole number) data from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807). Storage size is 8 bytes.

int

Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.

smallint

Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). Storage size is 2 bytes.

tinyint

Integer data from 0 through 255. Storage size is 1 byte.

float [ ( n ) ]

Is a floating point number data from - 1.79E + 308 through 1.79E + 308. n is the number of bits used to store the mantissa of the float number in scientific notation and thus dictates the precision and storage size. n must be a value from 1 through 53.

So How many bits in a byte...I think it's 8...but bol doesn't say what the default for float alone is

Looks like in EM in table design that float defaults to 8 bytes, so that would be half of what int is|||Queries should be a bit faster after that..

Ok, so this is you stated goal

supply us with DDL and the query that's "slow"

data type conversions are not where I would start for Perf Tuning|||exsqueeze me - shows my naivite of the subject. I think rather than floating point data types I should have said floating point calculations.

But in any event, if you want an accurate representation of the division of two integers a float is probably the wrong route.|||excuse me if I am wrong but I think one of the major drawbacks of floats is that you are not always guaranteed reproduceable results. I might be wrong about this.|||Ok - I found the link.

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=71391
It is really a display issue when you use a float. The problem is that float is internally a binary representation of the number, and the binary representation cannot always be converted directly to a decimal representation that is exactly equivalent. Float is intended for scientific applications where computational accuracy is the most important requirement.
My point was that Decimal is not always better (read more accurate) than Float. I probably should have made the point better & more succinctly though since in this case it is certainly better to use decimal.|||that's a great quote, pootle, thanks for following that up

better to use decimal? that depends on what kind of data you're storing

if it's money, yes :)

and pat will tell you it had better be DECIMAL(n,4), not 2 -- and then rounded by the front end if desired|||Have you ever divided two integer values?yup, and if i don't want a whole number answer, i use pat's trick, although mine is just slightly different:select 1.0 * col1 / col2:)

convert INT to BIGINT

Hi guys

We have a table A which has an Id column of type INT. There are currently about 260705246 rows in the table and growing at 100,000,000 rows a month. We will hit the limits of INT pretty soon at this rate. So I was asked to study the different options to convert the INT to BIGINT for the table. Conditions: (1) The downtime should be the least (2) the method should be 100% reliable and no unknown factors going into the rollout. I did my research and came up with a couple of methods:

(1) ALTER table ( I know this will not work)

(2) create a new column in the same table. repopulate the column with existing data using a job. modify all the stored procs/business objects to update/insert the new column instead of the old one. Drop the old column. rename the new column back to what it was ( or leave it as is). Recreate the indexes/FK constraints with the new column instead of the old column.

(3) create a new table B with BIGINT datatype. BCP the data from A into B. create all the indexes. drop the old tables. rename the new table to the old one.

I am suggesting method 3 as it requires least number of operations => less changes (and less places to) of screw up and less complicated.

If anyone else who has done this before can provide some feedback/do's and dont's etc I would apprecaite it.

Use SQL Management studio to change the column type from int to bigint. Click save. Tell everyone you are working hard on it, and go to lunch.

This will essentially do #1 if it's possible. If it's not, it will do #3 automatically for you. The only downside is that with that many rows (depending on how big each row is), this could take some significant time. You may want to try this on a test system first to make sure it will complete in the time you have allotted.

|||

I should have mentioned. We have SQL 2000 on production and its a 64 bit processor.

We tried #1 on an evaluation machine and it failed.

|||Right click and register the 64bits version in Enterprise manager of SQL Server 2000 32 bits and it becomes local, we used Oracle 9i the same way so I just tried it with SQL Server and it worked like a charm. So you can use Enterprise manager to change the data type or run ANSI SQL ALTER TABLE to change INT to BIGINT|||We already tried the ALTER TABLE approach and it failed.Normally I wouldnt be posting this question if its a simple ALTER statement issue. There are millions of records in the table. The server just froze when we tried it. And we cannot afford any downtime on the server for trials like these unless its a solid solution. Any other ideas?|||

Is this an identity column?

Please send me a private message with a script to recreate your table structure including indexes, and let me know if you have any foreign keys to or from this table and I'll get you an answer within a couple days. I got some disk space, processor cycles and time to spare ;-)

Anything else you can tell me about your production server would help. How many CPUs, RAM, and what disk topology? (Logs on raid-1, data on raid 5?) An approximate table size would help as well.

|||Create a blank database then create a new table with Big INT and run an INSERT INTO statement against the table to move the data, then move the new table into your database. If it works just truncate or drop the original table. The last option is to use DTS to move the table back into your database. Run some tests with a copy of your production database.|||This operation needs to be done on a PROD server which is 64 bit version. I believe DTS does not work on 64bit processor. We have tried traditional methods of (1) Insert Into (2) create a new BIGINT column in the same table, update the new column with the old col, drop the old col but with 900 million rows, it blows up. One thing is clear to me. Any solution would involve "batch" process. We cannot do a simple update or drop on the entire table. we need to do for a few hundred thousand rows at a time. As of now the only solution I have ( havent tried that out yet) that seems to work is to bcp out the table into multiple data files, and bacp back into a new table (again in batch) with BigInt alreadt defined and drop the old table and rename the new table to the old one. I am currently working on a replication issue and should be done by the end of the week. Early next week I should start doing some prototypes of the bcp solution and see how it works.|||Not really SQL Server 2005 comes with 64 bits eval versions use it to do the DTS now integration services operation to move the table back to your production SQL Server 2000 64 bits. I was a beta one tester of the product in 2001 the only known issues are pointer arithemetic problems not data migration. XP 64 bits eval can also be downloaded from Microsoft site. BTW both 64bits are AMD products because Intel's Itanium is still for server products.|||

Our PROD server is windows 2000 Data Center Edition. 64GB RAM; 32 processors. 64 bit processor.

|||SQL Server 2000 64bits does not run on Windows 2000 it runs on Windows 2003 64bits Microsoft sent us a pre beta 1 build of the product to do the testing in 2001. If it does run on Windows 2000 I am not aware of it. That said operating system is not important to what you want to do, that is move a table to SQL Server 2005 64bits on XP 64bits and sending the table back to SQL Server 2000 64bits. Just focus on data transfer between SQL Server.|||Yes. Almost every option we tried failed because of the huge data transfer. 900 mi rows is not easy to do trial and error. Yes you are right. I found out we have Win2003 Data center edition.|||

Option 1 may work, but it will take a very long time to complete.

Option 2 won't work at all, because this method won't work with identity fields.

Option 3 might work, but you would probably be better off just INSERT INTO ... SELECTing the data from one table to the other rather than using BCP.

I've got an option 4 I'm working on, but it's coming pretty slow. I got hammered last week because of the MS/Eolas spat and had to do some emergency changes for someone. Nearing a billion rows is a lot of data, took me almost 4 hours just to load test data, and that's not including building indexes.

I'm curious how your SAN performs compared to my desktop at home. A good SAN should put it to shame, but there are lots of people out there that don't know how to configure one. Coupled with the fact that you said an similiar attempt was made years ago and failed, unless you've upgraded your SAN, it's getting pretty old (And probably relatively slow). In any case, I'll have a solution for you in a couple of days (Sorry, I only run tests during the day when I'm not actively using the machine, cause the tests literally kill the machine... Multithreaded disk I/O wasn't my highest priority when I built it). I'm pretty sure I can get it down to a couple hours (meaning 2) downtime, if your SAN runs atleast as fast as my desktop. I'm sure the extra 31 processors and 62GB of ram will help some too, but not a whole lot.

|||

Thanks for your efforts Motley. I am sure our SAN must be up to date (I dont know much about the storage area yet). Time is exactly the problem I have. We do have an alternate site with exactly similar configuration as our PROD ( win 2k3 DC edition, 32 processors, 64 GB ram, SQL x64 edition etc) and if I have a solid plan I can ask for a few hours of access to the ALT site for my testing. But they will only let me use it if I have atleast reasonable confidence the solution work and when they do give me access I need to use every minute of it.

I do have other ideas in mind but like I said, I am not sure how they work with such huge data.

Thanks again.

|||

Well, my idea is that since the data load takes such a extreme amount of time to do, I'm building a process to create a duplicate table (tmpWhatever) in the background.

Unfortunately because of the sheer size of your table, the only way I see of efficiently doing so takes a few steps. Creating triggers to log changes to an audit log (insert, update,delete). Then begin loading data in the background row by row (More accurately small batch by small batch), and then once we have all the rows, replay the audit log on the temporary table (small batches) until we catch up. This should allow you (if you have the disk space to spare) to bring down the system at any point, run a stored procedure to make sure you've caught the last of the changes, drop your FK's, rename old to tmp2, rename tmp to old, and apply the FK's to new table, and you are done. I need to find out if the sp_rename stored procedure will let the indexes follow the rename or not. If it will then you'll need about 5 minutes of down time. If it won't, and you need to rebuild the indexes, then it'll take a while longer, but shouldn't be more than a couple hours.

The other question I have relates to the FK relationship. Is it valid to have a bigint primary key, as a foreign key into another table that is integer? If it is (and I don't really see why it wouldn't be, but it's possible it's not), then you can do each table separately, if it isn't then you'll need to do both processes at the same time.

Friday, February 10, 2012

convert comma separated values into rows withou using UDF

Hi,
I'm looking for a way to turn csv like 4,5,6,3 into rows without using
UDF, so it can be used in pure T-SQL only.
I want to use it in a code generated sql string, that will use these
values with an IN statement.
for example:
if column VAL contains 1,2,3
I would like to write something like:
SELECT * FROM x WHERE v IN (SELECT VAL ...) - this of course does not
work.
I also don't want to use CHARINDEX since this query should be as
efficient as possible.
I hope this can be done at all.
Thanks,
Eran.I think this is what you want:
DECLARE @.X NVARCHAR(4000)
SELECT @.X = 'SELECT columnList FROM x WHERE v IN (' + VAL + ')'
FROM tableName
EXEC(@.X)
But had the database been designed correctly, you wouldn't have to hope.
You could have simply used a join and avoided using dynamic SQL at all.
(1) You should never use SELECT * in production code.
(2) A column in a row (cell) should never have more than one value. In
other words, you should never store comma-separated values in a cell.
99.999% of the time, the presence of either of these is a sure sign of the
laziness, short-sightedness, and incompetence of the database designer or
developer.
"EranS" <eransevi@.yahoo.com> wrote in message
news:1124871159.442873.283030@.g14g2000cwa.googlegroups.com...
> Hi,
> I'm looking for a way to turn csv like 4,5,6,3 into rows without using
> UDF, so it can be used in pure T-SQL only.
> I want to use it in a code generated sql string, that will use these
> values with an IN statement.
> for example:
> if column VAL contains 1,2,3
> I would like to write something like:
> SELECT * FROM x WHERE v IN (SELECT VAL ...) - this of course does not
> work.
> I also don't want to use CHARINDEX since this query should be as
> efficient as possible.
> I hope this can be done at all.
> Thanks,
> Eran.
>|||thanks to brian heres a sample
use northwind
declare @.test nvarchar(4000)
declare @.values nvarchar (200)
set @.values='1,2,3,4'
set @.test='select * from employees where employeeid in ('+ (@.values)+')'
EXEC(@.test)
"Brian Selzer" wrote:

> I think this is what you want:
> DECLARE @.X NVARCHAR(4000)
> SELECT @.X = 'SELECT columnList FROM x WHERE v IN (' + VAL + ')'
> FROM tableName
> EXEC(@.X)
> But had the database been designed correctly, you wouldn't have to hope.
> You could have simply used a join and avoided using dynamic SQL at all.
> (1) You should never use SELECT * in production code.
> (2) A column in a row (cell) should never have more than one value. In
> other words, you should never store comma-separated values in a cell.
> 99.999% of the time, the presence of either of these is a sure sign of the
> laziness, short-sightedness, and incompetence of the database designer or
> developer.
>
> "EranS" <eransevi@.yahoo.com> wrote in message
> news:1124871159.442873.283030@.g14g2000cwa.googlegroups.com...
>
>|||Thanks Brian,
I can't run what you suggested since the values list should be
dynamically created when running the query, and it should both be in
one query.
This solution is only temporary until I'll normalize my tables better,
so I'm looking for a dirty way to do it. I guess I'll resort to using a
temporary table with the values in rows and then use it with the IN
clause. This won't be as fast as hoped but it should be better then
using a function.|||Take a look at this:
http://solidqualitylearning.com/Blo.../10/22/200.aspx
(by Dejan Sarka)
ML|||Eran, there are some issues with your request...

> I'm looking for a way to turn csv like 4,5,6,3 into rows without using
> UDF, so it can be used in pure T-SQL only.
A UDF is pure T-SQL.

> I want to use it in a code generated sql string, that will use these
> values with an IN statement.
> ...
> I also don't want to use CHARINDEX since this query should be as
> efficient as possible.
Using dynamic execution, you will end up with a different plan generated for
each unique string. Using the CHARINDEX method in a UDF that splits the arra
y
elements into multiple rows (or not encapsulated with a UDF), your code will
still be able to use an index on the table's join column, and reuse executio
n
plans.
That's really the way to go in this case.
My 2c (tested),
--
BG, SQL Server MVP
www.SolidQualityLearning.com
"EranS" wrote:

> Hi,
> I'm looking for a way to turn csv like 4,5,6,3 into rows without using
> UDF, so it can be used in pure T-SQL only.
> I want to use it in a code generated sql string, that will use these
> values with an IN statement.
> for example:
> if column VAL contains 1,2,3
> I would like to write something like:
> SELECT * FROM x WHERE v IN (SELECT VAL ...) - this of course does not
> work.
> I also don't want to use CHARINDEX since this query should be as
> efficient as possible.
> I hope this can be done at all.
> Thanks,
> Eran.
>|||Using a table function to split a string into rows can in most cases prove t
o
be much faster than using the IN operator, since the latter gets translated
into several OR clauses, which slow down the query processing.
On the other hand the table function returns a table of values that can be
joined to the other table(s) in your query, thus taking advantage of the muc
h
faster JOIN operation.
ML|||SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
IF OBJECT_ID ('dbo.fnBAS_utlSplitIDsIntoTable') IS NOT NULL --AND
OBJECTPROPERTY ( OBJECT_ID('dbo.fnBAS_utlSplitIDsIntoTable') ,
'IsinLineFunction' ) = 1
DROP FUNCTION dbo.fnBAS_utlSplitIDsIntoTable
GO
CREATE FUNCTION dbo.fnBAS_utlSplitIDsIntoTable (@.sIDList varchar(8000),
@.Delimeter char(1))
RETURNS TABLE AS
-- Version : $Id: fnBAS_utlSplitIDsIntoTable.sql,v 1.7 2005/05/09 20:11:33
vladimirm Exp $
/*
Usage:
declare @.IDlist varchar(500)
set @.idlist ='12,11,4,23455,13'
select * from dbo.fnBAS_utlSplitIDsIntoTable(@.IDList,',')
*/
RETURN
(
SELECT 1 - LEN(REPLACE(LEFT(@.sIDList, Number), @.Delimeter, SPACE(0))) +
Number AS [idx]
,SUBSTRING( @.sIDList, Number, CHARINDEX(@.Delimeter, @.sIDList +
@.Delimeter, Number) - Number) AS [intID]
FROM dbo.Numbers_8000
WHERE SUBSTRING(@.Delimeter + @.sIDList, Number, 1) = @.Delimeter
AND Number < LEN(@.sIDList) + 1
)
GO
"EranS" <eransevi@.yahoo.com> wrote in message
news:1124871159.442873.283030@.g14g2000cwa.googlegroups.com...
> Hi,
> I'm looking for a way to turn csv like 4,5,6,3 into rows without using
> UDF, so it can be used in pure T-SQL only.
> I want to use it in a code generated sql string, that will use these
> values with an IN statement.
> for example:
> if column VAL contains 1,2,3
> I would like to write something like:
> SELECT * FROM x WHERE v IN (SELECT VAL ...) - this of course does not
> work.
> I also don't want to use CHARINDEX since this query should be as
> efficient as possible.
> I hope this can be done at all.
> Thanks,
> Eran.
>

Convert columns

Hi,
I have some data in one table.
I need to get the data in the same table, into different rows.
I mean to say that, I have data like
InvNo InvAmt GstAmt
12 1900 79

and I need to get data like

InvNo Amt
12 1900
12 79

Can anyone help me as to how can i get data in this format.

Thanks.SELECT InvNo, InvAmt AS AMT
UNION ALL
SELECT InvNo, GstAmt AS AMT

???????????|||1. Create a second dummy table with the format that you want.
2. Transfer the data to the new table
3. Delete the original table
4. Rename the dummy table to the original name

Regards

Convert columnar data into rows

I have a table of data that needs to be converted to rows but with a way to identify for each row the column the row value came from.

Here's an example table:

Employee

FED

MEDI

SOCSEC

123

$100

$25

$70

234

$242

$54

$90

345

$75

$10

$55

Here's the format the data needs to be in after it's converted.

Employee

CodeType

Code

Amount

123

T

FED

$100

123

T

MEDI

$25

123

T

SOCSEC

$70

234

T

FED

$242

234

T

MEDI

$54

234

T

SOCSEC

$90

345

T

FED

$75

345

T

MEDI

$10

345

T

SOCSEC

$55

The CodeType will always be T.

This seems similar to some of the transpose-type samples but different enough (for me) to ask about.

Thank you for your help.

DECLARE @.Employee TABLE
(Employee int,
FED decimal(9,2),
MEDI decimal(9,2),
SOCSEC decimal(9,2))
INSERT @.Employee
SELECT 123, 100, 25, 70 UNION ALL
SELECT 234, 242, 54, 90 UNION ALL
SELECT 345, 75, 10, 55

SELECT Employee, 'T' AS CodeType, 'FED' AS Code, FED AS Amount
FROM @.Employee
UNION ALL
SELECT Employee, 'T' AS CodeType, 'MEDI' AS Code, MEDI AS Amount
FROM @.Employee
UNION ALL
SELECT Employee, 'T' AS CodeType, 'SOCSEC' AS Code, SOCSEC AS Amount
FROM @.Employee
ORDER BY Employee, Code

|||

You can do below:

select t.Employee

, 'T' as CodeType

, case c.n

when 1 then 'FED'

when 2 then 'MEDI'

when 3 then 'SOCSEC'

end as Code

, case c.n

when 1 then t.FED

when 2 then t.MEDI

when 3 then t.SOCSEC

end as Amount

from t

cross join (select 1 union all select 2 union all select 3) as c(n)

|||Thank you for your help. It is somewhat similar to the approach I took. The values were for illustration and will be much greater in quantity than the sample data I provided.

What I wound up doing was a series of select statements with a union all between them.|||Thank you for your answer. I'd like to use this but I'm a little lost on the case c.n portion and how that would be changed to fit the actual table and field names.|||

It's just creating a result set that is a single column named n with three rows holding the values 1, 2, and 3. Then you join to that result set with a cross join meaning you get three copies of each of your original rows matched with 1, 2, and 3 respectively. Then it uses that to determine which of the amounts and code types to use. In the example I gave you before it would be like this

DECLARE @.Counter int
SET @.Counter = 1
DECLARE @.Employee TABLE
(Employee int,
FED decimal(9,2),
MEDI decimal(9,2),
SOCSEC decimal(9,2))
INSERT @.Employee
SELECT 123, 100, 25, 70 UNION ALL
SELECT 234, 242, 54, 90 UNION ALL
SELECT 345, 75, 10, 55

select t.Employee
, 'T' as CodeType
, case c.n
when 1 then 'FED'
when 2 then 'MEDI'
when 3 then 'SOCSEC'
end as Code
, case c.n
when 1 then t.FED
when 2 then t.MEDI
when 3 then t.SOCSEC
end as Amount
from @.Employee t
cross join (select 1 union all select 2 union all select 3) as c(n)

Note that the as c(n) in the query is just assigning the column name that you use in the join, the last line of the query is exactly equivalent to

cross join (select 1 as n union all select 2 union all select 3) as c