萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mssql數據庫 >> SQLServer建立交叉表查詢

SQLServer建立交叉表查詢

 /*
使用方法,直接執行,傳入參數(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

copyright © 萬盛學電腦網 all rights reserved