Solved

Change sort field data type in a proc

Posted on 2013-05-13
6
301 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 40

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
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
LVL 40

Expert Comment

by:Sharath
ID: 39163689
0
 
LVL 40

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Query to return total 6 21
SQL 2008 with .NET 4.5.2 4 35
PolyServe for SQL server 13 32
sql 2016 data tools breakdown.. 1 13
There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

839 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