Solved

Change sort field data type in a proc

Posted on 2013-05-13
6
303 Views
Last Modified: 2013-05-13
at http://sqlfiddle.com/#!3/41435/1

There is a solution that produces Option 1, with field [fo] as int in the attached image. I want to revise it to produce Option 2 with field [fo] as varchar.

In case the code not found in the linke, please see:
create  TABLE tblSource(
f1 varchar(10)
,f2 varchar(10)
,f3 varchar(10)
,f4 varchar(10)
,f5 varchar(10)
)

create  TABLE tbltarget(
f1 varchar(10)
,f2 varchar(10)
,f3 varchar(10)
,f4 varchar(10)
,f5 varchar(10)
)

insert into tblSource (f1, f2, f3, f4, f5)
values('C','R','Q','Z', 'W'),(NULL,'X',NULL,'GZ', 'HW'),('D',NULL,NULL,'CZ', 'MW'),(NULL,'P','P','IZ', 'UW'),(NULL,'UX',NULL,'GZ', NULL)

go

Create procedure abcd
(
 @tblsource VARCHAR(100)
,@tbltarget varchar(100)
,@no_of_cols int
)
AS
BEGIN
declare @select varchar(max),@where varchar(max),@sql varchar(max),@tbd varchar(max),@sel varchar(max)

-- Get the column names in WHERE for PIVOT
SELECT @where = STUFF(( SELECT ',['+ COLUMN_NAME+']'
                FROM  INFORMATION_SCHEMA.columns where table_name = @tblsource and ORDINAL_POSITION <= @no_of_cols
               ORDER BY   ',['+ COLUMN_NAME+']'
                 FOR XML PATH('')), 1, 1, '') 

-- Get the column names in SELECT, replace NULL with empty string
SELECT @sel = STUFF(( SELECT ',ISNULL(['+ COLUMN_NAME+'],'''') [' + COLUMN_NAME + ']'
                FROM  INFORMATION_SCHEMA.columns where table_name = @tblsource and ORDINAL_POSITION <= @no_of_cols
               ORDER BY   ',['+ COLUMN_NAME+']'
                 FOR XML PATH('')), 1, 1, '') 

-- Get tbd
SELECT @tbd = STUFF(( SELECT ',[tbd]'
                FROM  INFORMATION_SCHEMA.columns where table_name = @tblsource and ORDINAL_POSITION <= @no_of_cols
               ORDER BY   ',['+ COLUMN_NAME+']'
                 FOR XML PATH('')), 1, 1, '')
				 
-- Create the target table
select @sql = '
IF OBJECT_ID('''+@tblTarget+''') IS NOT NULL
    DROP TABLE ' + @tblTarget +'
	select 0 f0,'+@where+ '
into '+@tblTarget+' from ' + @tblSource + ' where 1 = 0'
exec(@sql)

select @select = substring(select_list,1,len(select_list)-5)
  from (
select stuff((select 'SELECT ''' + COLUMN_NAME + ''' colname,'+COLUMN_NAME+' data FROM ' + @tblsource + ' WHERE ISNULL('+COLUMN_NAME+','''') <> '''' UNION '  
                from INFORMATION_SCHEMA.columns where table_name = @tblsource and ORDINAL_POSITION <= @no_of_cols
               order by COLUMN_NAME 
                 for xml path(''), 
                type).value('.','nvarchar(max)')
               , 1, 0, '') as select_list) t1 


select @sql = '
;with cte as (
select *,ROW_NUMBER() over (partition by colname order by data) rn
from ('+@select+') t1),
cte2 as (
select * from cte
union 
select colname,''<''+convert(varchar,rn)+''>'',-1  rn
  from (select colname,max(rn) rn 
          from cte
         group by colname) t1
 union 
select  colname, ''<tbd>'',0 rn from cte)
insert ' + @tblTarget + '
select case when rn <= 0 then 0 else rn end,'+@sel+ 
' from cte2
pivot(max(data) for colname in ('+@where+')) as p'

exec(@sql)

end

exec abcd 'tblSource','tblTarget',5
select * from tblTarget order by f0

Open in new window

tblTargetOptions.png
0
Comment
Question by:Mike Eghtebas
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 41

Expert Comment

by:Sharath
ID: 39163451
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 39163466
I hope some day I become as good as you are in designing stored procedures.

All is good except having 01, 02, 03 ... in place of 1, 2, 3.

This is because with 1, 2, 3, .... 19 it will sorted like:

1
19
2
3
0
 
LVL 35

Expert Comment

by:David Todd
ID: 39163644
Hi

@Sharath_123

Does the sort column need to be in the results set?

Why not sort on the leading zero version of the column, and display otherwise, which may or may not have leading spaces as per clients desire?

Just a thought. (No points please)

Regards
  David

PS I hate seeing things sorted

1
10
11
12
...
2
20
21
...
3
0
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 
LVL 41

Expert Comment

by:Sharath
ID: 39163689
0
 
LVL 41

Accepted Solution

by:
Sharath earned 500 total points
ID: 39163692
removed some unwanted code.

http://sqlfiddle.com/#!3/0e336b/1
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 39163711
Hi dtodd,

That was a very good suggestion. I appreciate the input.  But now, Sharath_123 has skillfully fixed it within the proc.

Regards,

Mike
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question