Solved

Change sort field data type in a proc

Posted on 2013-05-13
6
302 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
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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 Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

730 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