将表名传递给sql函数

时间:2014-08-01 20:26:16

标签: sql-server tsql stored-procedures sql-function

我有2个功能

当Employee.id = id

时,

frist找到员工的姓名

CREATE FUNCTION FindEmployeeName
 (
    @id bit 
 )
RETURNS varchar(32)
AS
BEGIN
    declare @name varchar(32) 
    set @name=( SELECT Employee.Id FROM Employee WHERE Id=@id)
RETURN  @name
END 

当Doctor.id = id:

时,第二次找到Doctor的名字
CREATE FUNCTION FindDoctorName
 (
    @id bit 
 )
RETURNS varchar(32)
AS
BEGIN
    declare @name varchar(32) 
    set @name=( SELECT Doctor.Id FROM Doctor WHERE Id=@id)
RETURN  @name
END 

现在,我可以拥有动态功能吗?

将表和ID传递给函数并返回名称?

CREATE FUNCTION FindEmployeeName
 (
    @id bit ,
    @tbl varcahr(32)
 )
RETURNS varchar(32)
AS
BEGIN
    declare @name varchar(32) 
    set @name=( SELECT @tbl.Id FROM @tbl WHERE Id=@id)
RETURN  @name
END 

有更好的方法吗?

编辑 我的架构是: enter image description here

3 个答案:

答案 0 :(得分:1)

不,你不能将表名作为变量传递给User defined function,因为你需要动态的sql来构建查询和执行,这是你在函数内部无法做到的事情,你需要使用存储过程为此...这样的事情......

CREATE PROCEDURE FindEmployeeName
    @id INT ,   --<-- I dont think you need BIT here, BIT can only 1 or 0
    @tbl sysname,
    @Name varchar(32) OUTPUT
AS
BEGIN
 SET NOCOUNT ON;

   DECLARE @SQL NVARCHAR(MAX);

  SET @SQL =  N' SELECT @Name = Name FROM ' + QUOTENAME(@tbl)
            + N' WHERE Id = @id '
 EXECUTE sp_executesql @SQL 
                      ,N'@id INT , @Name varchar(32) OUTPUT'
                      ,@Id
                      ,@Name OUTPUT
END 

答案 1 :(得分:1)

如果可能的话,我会在没有动态sql的情况下这样做。这是一种方法。基本上你最终会有三个程序,但性能非常值得。看看这篇探讨这种方法的性能优势的文章。 http://sqlinthewild.co.za/index.php/2009/09/15/multiple-execution-paths/

create procedure GetDoctorData
(
    @Id int
) as
    select Doctor.Id FROM Doctor WHERE Id=@id

go

create procedure GetEmployeeData
(
    @Id int
) as
    select Employee.Id FROM Employee WHERE Id=@id

go

create procedure GetPersonData
(
    @PersonType varchar(10)
    , @Id int
) as

    if @PersonType = 'Doctor'
        exec GetDoctorData @Id      

    if @PersonType = 'Employee'
        exec GetEmployeeData @Id

go

答案 2 :(得分:0)

DECLARE @id INT;                            
DECLARE @tblName VARCHAR(100);
SET @id = 1;
SET @tblName = 'Employee'

DECLARE @sqlString VARCHAR(500);
SET @sqlString = 'SELECT *'
                    + ' FROM ' +@tblName
                    + ' WHERE Id = ' + CAST(@id AS VARCHAR(100));
--PRINT(@sqlString);
EXEC (@sqlString);

我只是演示了如何将字符串转换为sql查询。 但是把这个建议当作肖恩·兰格&#39;尖。