2012-05-23 70 views
1

我是新來的sql編程;試圖開發這一功能讓誰擁有從視圖訪問的特定客戶數量行:SQL Server 2008 - 函數錯誤

ALTER FUNCTION [dbo].[fn_NumberOfVisit] 
(
@nv int 
) 
RETURNS varchar(500) 
AS 
BEGIN 
DECLARE @ret varchar(500) 

select * 
from (
    select 
     *, 
     rn = row_number() over (partition by ClientId order by VisitId) 
    from 
     Visit 
) activityWithRn 
inner join vw_MasterView on vw_MasterView.VisitId = activityWithRn.VisitId 
where activityWithRn.rn [email protected] 

RETURN @ret 

END 

我得到以下錯誤:

Select statements included within a function cannot return data to a client 

我會感謝您的支持。提前致謝。

+0

你有一個錯字 –

+0

而不是'設置@var =(select'你可能使用'選擇@var = ...'。 –

+0

@NikolaMarkovinović,這不會幫助。子查詢使用SELECT *這將是多個列,也不能分配給一個變量 - 即使它只是一列,它仍然是一些任意的行從多行結果來看,太多的其他問題也需要在評論中列出來 –

回答

0

錯誤是告訴你,你的子查詢返回的行數太多。你只需要返回一行就是你將結果分配給一個變量。

變化

set @Count = (select * 
from (
    select 
     *, 
     rn = row_number() over (partition by ClientId order by VisitId) 
    from 
     Visit 

set @Count = (select count(*) 
from (
    select 
     *, 
     rn = row_number() over (partition by ClientId order by VisitId) 
    from 
     Visit 
+0

謝謝這個作品 – hncl

1

你的問題是在這裏:

set @Count = (select * 
from (
    select 
     *, 

@count期待一個數字 - 你給它一幫行,請嘗試:

set @Count = (select Count(*) 
from (
    select 
+0

+1該OP也'RETURNS int',但實際返回變量是'nvarchar(50)' –

+0

謝謝我試圖在使用dbo.fn_NumberOfVisit(3)查詢中測試它,但它不起作用 – hncl

+0

當我使用Count (*)我得到行數;我需要顯示這些行的內容。謝謝 – hncl