SQLServer建立交叉表查询

网络整理 - 08-20

 /*
使用方法,直接执行,传入参数(series_guid, 查询条件)返回一个数据集
如:
查询该系列Cylindrical1下所有产品
dbo.P_GetSeriesProductDetail 'Cylindrical1',''
查询系列Cylindrical1下含有BK-1的产品
dbo.P_GetSeriesProductDetail 'Cylindrical1','product_name like ''%BK-1%'''
*/
CREATE PROCEDURE P_GetSeriesProductDetail(@series_guid varchar(40), @condition varchar(1000))
AS
DECLARE @ParamNo nvarchar(5)
DECLARE @SQL nvarchar(4000)
Set @SQL=''
DECLARE P_cursor CURSOR
local
fast_forward
FOR SELECT param_no FROM V_product_params where series_guid=@series_guid
OPEN P_cursor


FETCH next FROM P_cursor INTO @ParamNo
WHILE (@@fetch_status = 0)
BEGIN
Set @SQL = @SQL + ',MAX(CASE param_no WHEN ' + @ParamNo + ' THEN param_value ELSE '''' END) AS F' + @ParamNo + char(13)
FETCH next FROM P_cursor INTO @ParamNo
END


CLOSE P_cursor
DEALLOCATE P_cursor
Set @SQL='SELECT type_guid, series_guid, product_no, product_name' + @SQL + '
FROM V_product_params WHERE series_guid=''' + @series_guid + ''''
if (LTrim(@condition)<>'')
Set @SQL= @SQL + ' and ' + @condition
Set @SQL= @SQL + '
GROUP BY type_guid, series_guid, product_no, product_name'


Print @SQL
Execute sp_executesql @SQL