Solved

MS SQL Function issue

Posted on 2013-01-17
2
318 Views
Last Modified: 2013-01-17
Hi guys,

I'm new to SQL functions, and have been using them create a few "computed column" in a table for an online "competition" generating points score.

I have an issue in that the function is constantly returning a count of 0, when it should be responding back with a number...

I have used the following script to create the function..

CREATE FUNCTION [dbo].[FBCount] (@TeamID NVARCHAR)
RETURNS NVARCHAR
AS BEGIN
    DECLARE @FBCount INT

    SELECT @FBCount = COUNT(DISTINCT fbuser) FROM dbo.FBtable WHERE fbcode = TeamID

    RETURN @FBCount
END

And added ([dbo].[FBCount]([RandomCode])) to the computed column formula - where "RandomCode" is a 20 character random string - an example of this is OVU9ANYL0CBQ0NBVMFIL.  Randomcode is a column of NVARCHAR(255)

If I just try a sql "select" using SELECT COUNT(DISTINCT fbuser) FROM dbo.FBtable WHERE fbcode = 'OVU9ANYL0CBQ0NBVMFIL' it works fine.

So where am I going wrong??? is it something to do with quotes?

Thanks
0
Comment
Question by:BenjyAdams
2 Comments
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 250 total points
Comment Utility
your input type is nvarchar, which is equivalent to nvarchar(1)  it should be nvarchar(255)

CREATE FUNCTION [dbo].[FBCount] (@TeamID NVARCHAR(255) )
RETURNS int
AS BEGIN
    DECLARE @FBCount INT

    SELECT @FBCount = COUNT(DISTINCT fbuser) FROM dbo.FBtable WHERE fbcode = TeamID

    RETURN @FBCount
END
0
 

Author Closing Comment

by:BenjyAdams
Comment Utility
Bingo - thanks....so simple...but had stumped me :)
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Join & Write a Comment

Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how the fundamental information of how to create a table.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now