If exists (select * From DBO. sysobjects Where id = object_id (n' [DBO]. [p_zj] ') and objectproperty (ID, n' isprocedure') = 1) Drop procedure [DBO]. [p_zj] Go/* -- Common row-column swapping stored procedure: swaps the specified table by specified field -- Producer build 2004.04 -- -- Example -- Test Data Create Table (Category varchar (10), male decimal (20, 1), female decimal (20, 1 )) Insert table select 'fiction ', 38.0, 59.2 Union all select 'prose ", 18.9, 30.6 Union all select 'philosophical, 16.2, 10.2 -- The Conversion Result is required. /* Gender novels prose Philosophy ------------------- Male 38.0 18.9 16.2 Female 59.2 30.6 10.2 */ -- Call a stored procedure Exec p_zj 'table', 'category', 'Gender' -- Delete test Drop table */ Create proc p_zj @ Tbname sysname, -- Name of the table to be processed @ Fdname sysname, -- used as the conversion column name @ New_fdname sysname = ''-- specifies the column name for the converted Column As Declare @ S1 varchar (8000), @ S2 varchar (8000) , @ S3 varchar (8000), @ S4 varchar (8000), @ S5 varchar (8000) , @ I varchar (10) Select @ S1 = '', @ S2 ='', @ S3 = '', @ S4 ='', @ S5 = '', @ I = '0' Select @ S1 = @ S1 + ', @' + @ I + 'varchar (8000 )' , @ S2 = @ S2 + ', @' + @ I + '= ''' + case isnull (@ new_fdname, '') When ''then'' Else @ new_fdname + '= 'end + ''' + name + '''''''' --, @ S2 = @ S2 + ', @' + @ I + '= ''Gender = ''' + name + '''''''' , @ S3 = @ S3 +' Select @ '+ @ I +' = @ '+ @ I +' + '', [''+ ['+ @ fdname +'] +''] = ''+ Cast (['+ name +'] As varchar) from ['+ @ tbname +']' , @ S4 = @ S4 + ', @' + @ I + '= 'select' + @' + @ I , @ S5 = @ S5 + '+ ''union all'' + @' + @ I , @ I = cast (@ I as INT) + 1 From syscolumns Where object_id (@ tbname) = ID and name <> @ fdname Select @ S1 = substring (@ S1, 2,8000) , @ S2 = substring (@ S2, 2,8000) , @ S4 = substring (@ S4, 2,8000) , @ S5 = substring (@ S5, 16,8000) Exec ('desc' + @ S1 +' Select '+ @ S2 + @ S3 +' Select '+ @ S4 +' Exec ('+ @ S5 + ')') Go |