我有一个转置表格的动态pivot
/unpivot
脚本。这足够动态,可以返回我想要的某些列并使用动态列。
我正在寻找的是将其转换为 aUDF
或 aVIEW
以便我可以将其加入其他表。
请帮忙。
ALTER PROC [dbo].[uspGetUserByValues]
(
@Select NVARCHAR(4000) = '*',
@Where NVARCHAR(4000) = NULL,
@OrderBy NVARCHAR(4000) = NULL
)
AS
BEGIN
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',P.' + QUOTENAME(PropertyDescription)
from System_Properties
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ', M.Email, C.Company_Name, C.Company_Type_ID, U.UserName, ISNULL(SMS.SMSProfiles,0) SMSProfiles, U.UserID
from
(
select PropertyDescription, UP.UserID, PropertyValue
from User_Properties UP
JOIN System_Properties SP ON UP.PropertyID = SP.PropertyID
JOIN aspnet_Membership M ON UP.UserID = M.UserID
) X
pivot
(
min(PropertyValue)
for PropertyDescription in (' + REPLACE(@cols,'P.','') + ')
) P
JOIN aspnet_Membership M ON P.UserID = M.UserID
JOIN aspnet_Users U on P.UserID = U.UserID
JOIN Companies C ON C.Company_ID = P.Company_ID
LEFT JOIN (SELECT UserId, COUNT(Users_SMS_Profile_ID) SMSProfiles
FROM Users_SMS_Profile GROUP BY UserID ) SMS ON SMS.UserID = P.UserID
'
SET @query = 'SELECT ' + @Select + ' FROM ('+ @query +') A'
IF ISNULL(@Where,'NULL') != 'NULL'
BEGIN
SET @query = @query + ' WHERE ' + @Where
END
IF ISNULL(@OrderBy,'NULL') != 'NULL'
BEGIN
SET @query = @query + ' ORDER BY ' + @OrderBy
END
execute(@query)
--PRINT(@query)
END