在UDF from子句中使用参数

时间:2011-06-23 13:46:36

标签: sql-server-2008 stored-procedures user-defined-functions

我在SQL Server 2008中有一个用户定义的函数。这是:

CREATE FUNCTION [dbo].[GetAddressByEntityNameAndId] 
(
-- Add the parameters for the function here
@entityName varchar (100),
@parentEntityId int
)
RETURNS varchar(300)
AS
BEGIN
-- Declare the return variable here
DECLARE @Address varchar(300)

if(@entityName = 'Staff')
BEGIN

    select @Address = ca.Address + ' ' + ca.City + ' ' + ca.State + ' ' + ca.ZipCode
    from @entityName cc 
    inner join  ContactAddress ca on ca.ParentEntityId = cc.Id 
    inner join EntityName en on en.Id = ca.EntityNameId and en.Name = @entityName 
    inner join GeneralLookup gl on ca.glAddressTypeId = gl.Id and gl.LookupItem = 'Primary' 
    where cc.Id = @parentEntityId

END 
-- Return the result of the function
RETURN @Address

END

但它没有被执行。错误信息是:

Must declare the table variable "@entityName".

任何帮助都将不胜感激。

更新:

好的,现在我有另一个问题。这是我的SP:

ALTER PROCEDURE [dbo].[spGetStaffsAndClients]

AS
BEGIN

declare @Address varchar (100)
declare @Apartment varchar (100)
declare @City varchar (100)
declare @State varchar (10)
declare @Zip varchar (10)
declare @County varchar (100)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here

/* Get Client's Residence */

select dbo.GetClientFullName(s.FirstName, s.MiddleInit, s.LastName) StaffName, 
dbo.GetStaffTitlesById(s.Id) StaffTitle,
dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) ClientName, 
dbo.GetAddressByEntityNameAndId('Client', c.Id) ClientAddress

from ClientStaff cs 
left outer join Staff s on cs.StaffId = s.Id 
left outer join Client c on cs.ClientId = c.Id

END

这是UDF:

ALTER FUNCTION [dbo].[GetAddressByEntityNameAndId] 
(
-- Add the parameters for the function here
@entityName varchar (100),
@parentEntityId int
)
RETURNS varchar(300)
AS
BEGIN
-- Declare the return variable here
DECLARE @Address varchar(300)

if(@entityName = 'Client')
BEGIN

    select @Address = ca.Address + ' ' + ca.City + ' ' + ca.State + ' ' + ca.ZipCode
    from Client cc 
    inner join  ContactAddress ca on ca.ParentEntityId = cc.Id 
    inner join EntityName en on en.Id = ca.EntityNameId and en.Name = cc.Id 
    inner join GeneralLookup gl on ca.glAddressTypeId = gl.Id and gl.LookupItem = 'Primary' 
    where cc.Id = @parentEntityId

END 
-- Return the result of the function
RETURN @Address

END

我正在执行SP并收到错误: Conversion failed when converting the varchar value 'Client' to data type int. 我无法解决问题。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

您不能在from子句中使用@entityName而不是表名。由于您只在Staff上进行测试,因此您可以使用from Staff cc。我知道在from子句中有一个变量表名的唯一方法是使用动态SQL。我认为你不能在函数中使用动态SQL。

在此处了解有关动态查询的详情http://www.sommarskog.se/dynamic_sql.html