1

我試圖做一個函數返回varchar,但我不能因爲我在裏面使用CREATE TABLE,當我用一個過程創建它時,我無法返回一個值。返回varchar的過程

我想知道你是否有一些建議。

我這樣做是爲了讓一個字符串與電子郵件分隔「;」所以我可以將所有「經理」郵件放在一個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 @[email protected]@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 [email protected]) + ';' 
     set @counter = @counter+1 
    END 
    drop table #temp 
    return cast (@mails as varchar (200)) 
END 
+0

不要忘了標記它作爲acceepted,如果你有你想要的信息 – 2013-03-27 13:07:00

+0

你可以使用表變量,而不是臨時表,然後你可以使用函數。 – 2013-11-12 21:04:47

回答

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

+0

+1一個輸出參數是優選的,即使對於一個整數 – Andomar 2013-03-27 11:17:52

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 
+0

ty爲你幫助它解決我使用的輸出:) – DnL 2013-03-27 18:36:53

+0

遊標必須避免。您可以使用'select @emails = @emails + hr.Employees ...'的電子郵件 – 2013-11-12 21:09:12

0

您可以使用表變量來代替臨時表。在這種情況下,您可以繼續使用UDF。