Home >Database >Mysql Tutorial >SQLServer建立交叉表查询

SQLServer建立交叉表查询

WBOY
WBOYOriginal
2016-06-07 16:17:452200browse

/* 使用方法,直接执行,传入参数(series_guid, 查询条件)返回一个数据集 如: 查询该系列Cylindrical1下所有产品 dbo.P_GetSeriesProductDetail 'Cylindrical1','' 查询系列Cylindrical1下含有BK-1的产品 dbo.P_GetSeriesProductDetail 'Cylindrical1','p

 /*
使用方法,直接执行,传入参数(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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn