1、/定义存储过程.Create PROCEDURE Usp_StatictableName nvarchar(50),groupCol nvarchar(50), -分组字段.staticCol nvarchar(50), -统计字段.showCol nvarchar(50), -表头字段.opera nvarchar(50) -聚会函数.ASdeclare SQL nvarchar(max), proColumn nvarchar(50) -存储游标执行的列.execute (Declare curCol Cursor for select distinct +showCol+ from +t
2、ableName+ for read only) -游标.-一,对于只有 “表名“,“字段“等的拼接,只需要通过字符串直接拼接(SQL 中只支持单引号,表示字符串常量):表字段有:FOrderNum (订单号 ),FGoodName(商品名), FOrderQuantity(数量),FCustomerName(用户名).需求表达式:select FOrderNum, sum(FOrderQuantity) as 汇总.写入表达式:SQL = select +groupCol+,+opera+(+staticCol+) as 汇总 二, 对于含有指定字符串常量( 该常量是动态传递过来的).则需要
3、 “分割后再连接“:需求表达式:(电风扇是游标 curCol获得的商品名)1)列出需求 ,when 电风扇 then fileName else null End as 电风扇2)字符转义 ,when 电风扇 then fileName else null End as 电风扇因为“商品名是动态传递过来的,所以进行分割:when |电风扇 | then |fieldName| else null end) as |电风扇|第一个分割位置的前面是半截字符串,你当然得补上一个单引号了,后面是一个字符串变量,就直接+了2)合并: when +proColumn+then+staticCol+else null end as +proColumn+“.-其中,when 后面的第一个单引号转义第二个单引号,第三个单引号为补充半截字符串.