我尝试创建一个返回varchar
的函数,但我不能,因为我在里面使用CREATE TABLE
,当我用一个过程创建它时,我无法返回值。
我想知道你是否有一些建议。
我这样做只是为了创建一个字符串,其中包含以“;”分隔的电子邮件所以我可以将所有“经理”邮件放在一个varchar中(对于收件人)。
ALTER procedure [dbo].[Manager_email]
AS
BEGIN
declare @mails varchar (max),
@number_of_mails int,
@counter int
set @counter=2
create table #temp ( id int identity, email varchar(30))
insert into #temp (email)
select Email
from hr.Employees
where lower (EmpRole) like 'manager'
set @number_of_mails=@@ROWCOUNT
set @mails = (select email from #temp where id =1 ) + ';'
while @counter <= @number_of_mails
BEGIN
set @mails = @mails + (select email from #temp where id =@counter ) + ';'
set @counter = @counter+1
END
drop table #temp
return cast (@mails as varchar (200))
END
答案 0 :(得分:4)
你只能从程序中返回整数值,如果你想从程序中返回varchar值,那么在程序中使用输出变量就好了。
实施例
CREATE PROCEDURE Sales.uspGetEmployeeSalesYTD
@SalesPerson nvarchar(50),
@SalesYTD money OUTPUT
AS
SET NOCOUNT ON;
SELECT @SalesYTD = SalesYTD
FROM Sales.SalesPerson AS sp
JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID
WHERE LastName = @SalesPerson;
RETURN
就像上面的过程从程序中返回@SalesYTD
一样。
您可以在MSDN上查看完整帖子:Returning Data by Using OUTPUT Parameters
答案 1 :(得分:1)
您可以使用功能
CREATE FUNCTION Manager_email ()
RETURNS varchar(max)
AS
BEGIN
declare @email varchar(30)
declare @emails varchar(max)
set @emails = ''
declare cur cursor for
select Email
from hr.Employees
where lower (EmpRole) like 'manager'
open cur
fetch next from cur into @email
while @@fetch_status = 0
begin
set @emails = @emails + @email + ';'
fetch next from cur into @email
end
close cur
deallocate cur
return @emails
END
答案 2 :(得分:0)
您可以使用表变量而不是临时表。在这种情况下,您可以继续使用UDF。