2012-05-23 73 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