最近朋友有个需求:将产品中为“期刊”的书品以行转列的形式展现,同时需要关联工单主表及工单明细表,显示内容为,工单号、操作日期、产品名称及数量,由于期刊的产品数量较多,静态的虽然可以实现,但不利于后续内容的添加,就想着如何能以动态的形式展现,自动拼接sql语句处理,具体实现过程如下。
产品信息表需用到的字段内容:
select ProductCode,Name from ComProduct where ProductType ='20'
工单需要用到的内容:
select JobNo,ProductCode,Quantity from WmsJobDtl
通过搜索资料,终于完成动态拼接SQL语句,具体的存储过程如下:
CREATE PROCEDURE 期刊核算汇总表 as begin DECLARE @sql VARCHAR(8000) DECLARE @COLUMN VARCHAR(8000) SELECT @sql= ISNULL(@sql+',','')+ '['+ProductName+']' ,@COLUMN= ISNULL(@COLUMN,'')+', '+ProductName FROM (select wj.JobNo ,wj.StockDate, a.ProductName ,sum(wjd.Quantity) as TQty from (select ProductCode, Name as ProductName from ComProduct where ProductType ='20' ) as a inner join WmsJobDtl wjd on a.ProductCode = wjd.ProductCode inner join WmsJob wj on wj.JobNo = wjd.JobNo where wj.Status = 'X' group by wj.JobNo ,wj.StockDate, a.ProductName) as cc GROUP BY ProductName SET @sql=' select * from (select wj.JobNo ,wj.StockDate, a.ProductName ,sum(wjd.Quantity) as TQty from (select ProductCode, Name as ProductName from ComProduct where ProductType =''20'' ) as a inner join WmsJobDtl wjd on a.ProductCode = wjd.ProductCode inner join WmsJob wj on wj.JobNo = wjd.JobNo where wj.Status = ''X'' group by wj.JobNo ,wj.StockDate, a.ProductName ) as dddd pivot (max(TQty) for ProductName in ('+@sql+'))a' exec (@sql) end
可惜,没有解决NULL值得问题,如有能解决的朋友,欢迎留言,非常感谢。