?
Solved

Change sort field data type in a proc

Posted on 2013-05-13
6
Medium Priority
?
304 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
Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

 
LVL 41

Expert Comment

by:Sharath
ID: 39163689
0
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

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 …
In this article I will describe the Backup & Restore 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.
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

752 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