2017-03-29 97 views
1

我在這裏要做的是執行GetValue3@ID並獲取列出@fullname,@ phonenumber,@email,@city的@results在存儲函數中選擇語句時遇到問題

我得到2個錯誤,我一直想弄清楚如何解決這兩個問題。

錯誤#1

選擇語句包含一個函數中不能將數據返回到客戶端

錯誤#2

一個值分配給變量A選擇語句不得與數據檢索結合使用

我該怎麼辦?

Create Function GetValue3 (@ID INT) 
returns nvarchar(350) 
as 
begin 
    declare @results nvarchar(350) 
    declare @fullname nvarchar(75) 
    declare @phonenumber nvarchar(100) 
    declare @email nvarchar(50) 
    declare @city nvarchar(20) 

    select -- this is where I get the first error. 
     @fullname = p.Full_Name, 
     @phonenumber = c.Phone, 
     @email = c.Email, 
     @city = c.CityID, 
     @results = @fullname, 
     @phonenumber, @email, @city -- this is where I get the 2nd error. 
    from 
     d_People p, d_Contacts c 
    where 
     c.PeopleID = p.PeopleID 
     and p.PeopleID = @ID; 

    return @results 
end 
+0

mysql或SQL-Server(mssql)? – Jens

+0

您在每個DECLARE行後都會錯過';' – Jens

+0

這是一個SQL-Server數據庫。我還加上了所有的「;」在聲明結束時。 –

回答

0

你可以改變你的代碼下面,我想它會給你,你找什麼:

create function GetValue3 (@ID int) 
returns nvarchar(350) 
as 
begin 
    declare @result nvarchar(350) 

    select 
     @result = p.Full_Name + ',' + c.Phone + ',' + c.Email + ',' + c.CityID 
    from d_People p 
     , d_Contacts c 
    where c.PeopleID = p.PeopleID 
     and p.PeopleID = @ID; 

    return @result 
end 

原因你得到的錯誤是因爲在SELECT聲明中,您可以或者爲變量分配一個值返回n數據,你不能混合在一起。

而且,@fullName@phoneNumber等的值不被單獨地在SELECT的頂部設置,然後「向下移動」,使得在@results = @fullname, @phonenumber, @email, @city它們是可見的。

+0

謝謝您解決了我的錯誤。 –

+0

由於我有1個人ID和許多聯繫人ID,因此我會如何返回超過1個聯繫人? –

+0

@AlexanderHristov然後你需要一個[存儲過程](https://docs.microsoft.com/en-us/sql/t-sql/statements/create-procedure-transact-sql)或[表值函數] (https://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx)。 –

1

嘗試用下面的代碼:

Create Function GetValue3 (@ID INT) 
    returns nvarchar(350) 
    as 
    begin 
     declare @results nvarchar(350) 
     declare @fullname nvarchar(75) 
     declare @phonenumber nvarchar(100) 
     declare @email nvarchar(50) 
     declare @city nvarchar(20) 

      select 

       @fullname = p.Full_Name, 
       @phonenumber = c.Phone, 
       @email = c.Email, 
       @city = c.CityID, 
       @results = @fullname +','+ @phonenumber +','+ @email +','+ @city 
       from d_People p, d_Contacts c 
       where c.PeopleID=p.PeopleID and [email protected]; 

    return @results 
    end 
+0

謝謝,我是新的,我不知道我必須告訴它+','+ @ nextparameter。 –

+0

如果我的答案幫助您解決了您的問題,請將其標記爲有用 –

0
Create Function GetValue3 (@ID INT) 
returns table 
as 
return select p.Full_Name, c.Phone, c.Email, c.CityID 
       from d_People p, d_Contacts c 
       where c.PeopleID=p.PeopleID and [email protected];