我有一个标量值[返回类型nvarchar]函数,它返回一个动态查询字符串。 让我的功能如下......
CREATE FUNCTION ABC
(
)
RETURNS nvarchar(MAX)
AS
BEGIN
return 'Select * from Table1'
END
我想按照以下方式执行它......
Select * from dbo.ABC()
或
Select * from EXEC(dbo.ABC())
在SQL Server 2012中可以吗? 我必须在不使用openquery的情况下完成它。
-- My Actual Function --
ALTER FUNCTION [dbo].[RowToColumn]
(
-- Add the parameters for the function here
)
RETURNS nvarchar(MAX)
AS
BEGIN
DECLARE @PunchList nvarchar(MAX)
DECLARE @PunchListTOP nvarchar(MAX)
DECLARE @SQL nvarchar(MAX)
DECLARE @Flag INT
SET @PunchList = ''
SET @PunchListTOP = ''
DECLARE @I INT
SET @Flag = (select MAX(X) as MMAX from (select Employee_ID,Date_Of_Working, count(Date_Of_Working) as X from DataInOneRowStep3 group by Date_Of_Working ,Employee_ID ) A)
Set @I =1
WHILE (@I<= @Flag)
BEGIN
if (@PunchList = '' )
BEGIN
Set @PunchList = 'Punch_' + CONVERT(varchar, @I)
Set @PunchListTOP = ' MAX(Punch_' + CONVERT(varchar, @I) +') Punch_' + CONVERT(varchar, @I)
END
else
BEGIN
Set @PunchList = @PunchList + ',' + 'Punch_' + CONVERT(varchar, @I)
Set @PunchListTOP =@PunchListTOP +','+ ' MAX(Punch_' + CONVERT(varchar, @I) +') Punch_' + CONVERT(varchar, @I)
END
SET @I = @I + 1
END
SET @SQL ='SELECT Employee_Id,Date_OF_Working,Shift_Id,'+@PunchListTOP+' FROM (
SELECT * from DataInOneRowStep4
) as s
PIVOT
(
MAX(EntryTime)
FOR Punch IN ('+@PunchList+')
)AS piv group by Employee_Id,Date_OF_Working,Shift_Id'
RETURN @SQL
END