Solved

Change sort field data type in a proc

Posted on 2013-05-13
6
293 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
Comment Utility
0
 
LVL 33

Author Comment

by:Mike Eghtebas
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 40

Expert Comment

by:Sharath
Comment Utility
0
 
LVL 40

Accepted Solution

by:
Sharath earned 500 total points
Comment Utility
removed some unwanted code.

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

Author Comment

by:Mike Eghtebas
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now