如何在SQL中的执行键内编写函数

时间:2019-03-25 12:28:46

标签: sql-server tsql dynamic-sql stored-functions

Create Function fnRMatrixColorGet1(
@RMID varchar(20)
)
returns varchar(100)

as
begin

EXEC (N'SELECT ' + 'C'+@RMID + ' FROM vwemployeeget where empid='+@RMID) 
return 
end

1 个答案:

答案 0 :(得分:0)

正如戈登在评论中所写,SQL Server中用户定义的函数无法执行动态SQL。

来自Create User-defined Functions:

  
      
  • 用户定义的函数不能使用动态SQL或临时表。允许使用表变量。
  •   

但是,您可以创建一个存储过程来做到这一点:

CREATE PROCEDURE stpRMatrixColorGet1
(
    @RMID varchar(20)
    @MatrixColor varchar(100) OUTPUT
)
AS

DECLARE @Sql nvarchar(4000),
        @Column sysname = N'C' + @RMID;

-- White list column name since it can't be parameterized
IF EXISTS
(
    SELECT 1
    FROM Information_Schema.Columns
    WHERE Table_Name = 'vwemployeeget'
    AND Column_Name = @Column
)
BEGIN

    SET @SQL = N'SELECT @MatrixColor = QUOTENAME('+ @Column +') FROM vwemployeeget where empid = @RMID'

    -- Safely execute dynamic SQL using sp_ExecuteSql
    EXEC sp_ExecuteSql 
                        @Sql, 
                        N'@RMID varchar(20), @MatrixColor varchar(100) OUTPUT', 
                        @RMID, 
                        @MatrixColor OUTPUT
END