将列数据当成列名并查询查询数据

一、需求

sqlserver使用存储过程将列数据当成列名并查询查询数据

二、模拟表

idnamesizenumber
1aS4
2aM8
3aL4
4aM7
5cS4
6bM8
7cS4
8dM8
9dS4
10eM8
11dS4
12dM8

三、要实现的效果

idnameSML
1a4154
2b080

四、思路

  1. 先把Size全查询出来,作为列名,创建临时表

    1. 从表中读取size,并存入临时表
    	IF Object_Id('tempdb.dbo.##size_table') is not null  
    		drop table ##size_table  
    	select *
    	into ##size_table
    	from (
    		select distinct Size from table
    	) a
    
    1. 使用for xml path(‘’)将临时表数据以xml的形式读取并拼装成字符串
    	declare @size_columns varchar(max) = ''
    	set @size_columns = ( select '[' + Size + '] int,'
    			  from ##size_table 
    			  for xml path('')	
    			)
    
    1. 创建临时表
    	IF Object_Id('tempdb.dbo.##table') is not null  
    	drop table ##table  
    
    	declare @sql1 nvarchar(max) 
    	set @sql1= N'
      		create table ##table  
      		(  
    		   id int,  
    		   name varchar(10),'
    		   + @size_columns)'
      	exec( @sql1 )
    
  2. 查询数据时,根据name分组查询,根据size的不同,计算number的和

    1. 读取临时表,拼装成size列名
    	declare @size_insert nvarchar(max)
    	set @size_insert = ( select ',[' + Size + ']' from ##size_table for xml path('') ) 
    
    1. 拼装成case方式,用于读取数据
    	declare @size_Pcs_Qty nvarchar(max)
    	set @size_Pcs_Qty = ( select ',sum(case when b.Size=''' + Size + ''' then Pcs_Qty else 0 end) as [' + Size + ']'
    			  from ##size_table 
    			  for xml path('')	
    			)
    
    1. 将数据插入临时表
    	declare @sql2 nvarchar(max)
    	set @sql2 = N'
    	insert ##table  
    	(  
    	 id, name' + @size_insert )  
    	select id, name' + @size_Pcs_Qty + 'from table'
    
  3. 最后查询临时表数据

    	select * from ##table
    

注意事项

  1. 临时表要使用##,因为#作用域只是存在于一个exec中,别的地方无法调用
  2. 不可使用##,会影响数据库服务器性能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值