Simple math in T-SQL
I am using a Scalar-Valued Function to find out if a user of the system has images, audio files or videos in their profile.
When I search through members I want to order the members by amount of media they have. So for example a user with all media (videos, audio and image开发者_Go百科s) would get 3, 1 point for each media they have. If they have 2 media(images and video) but no audio they would get 2. This would be listed after all the users that have all 3 media.
The stored procedure has this:
SELECT
a.MemberID,
a.UserName,
a.LastLogin,
a.City,
b.Abbr,
c.Country,
a.AvatarMed,
a.Gender,
sbuser.sf_MemberHasImages(a.MemberID),
sbuser.sf_MemberHasVideo(a.MemberID),
sbuser.sf_MemberHasAudio(a.MemberID),
d.Domain,
sbuser.sf_DisplayName(a.MemberID),
a.CreateDate,
a.Claimed,
a.ProfileTypeID,
a.Zip,
a.PhoneNbr,
a.PrPhone
FROM Member a
LEFT JOIN State b ON b.StateID = a.StateID
INNER JOIN Country c ON c.countryID = a.CountryID
INNER JOIN Region d ON d.RegionID = a.MemberREgionID
WHERE ProfileTypeID IS NOT NULL
AND (sbuser.sf_DisplayName(a.MemberID) LIKE @UserName + '%')
AND a.MemberID <> @MemberID
ORDER BY a.Claimed DESC, a.AvatarTiny DESC, sbuser.sf_MemberHasMedia(a.MemberID)
If you note the order by, it contains the following:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [sbuser].[sf_MemberHasMedia](@MemberID bigint)
RETURNS BIT
AS
BEGIN
DECLARE @OUTSTR INT
DECLARE @OUT1 BIT
DECLARE @OUT2 BIT
DECLARE @OUT3 BIT
SET @OUT1 = (SELECT CAST(COUNT(MemberAudioID) AS BIT) FROM MemberAudio
WHERE MemberID @MemberID)
RETURN @OUTSTR = @OUT1
END
RETURNS BIT
AS
BEGIN
SET @OUT2 = (SELECT CAST(COUNT(a.MemberImgID) AS BIT)
From MemberImg a
INNER JOIN MemberImgGallery b ON b.MemberImgGalleryID=a.MemberImgGalleryID
WHERE b.MemberID = @MemberID)
RETURN @OUTSTR = @OUTSTR + @OUT2
END
RETURNS BIT
AS
BEGIN
SET @OUT3 = (SELECT CAST(COUNT(MemberVideoID) AS BIT) FROM MemberVideo
WHERE MemberID = @MemberID)
RETURN @OUTSTR = @OUTSTR + @OUT3
END
I am lost in the logic of this, and it should be easy. Any help would be greatly appreciated.
Many thanks, Paul
I've attempted to clean the syntax of the function up a little. The key point is that the return type of the function should be an INT instead of a BIT.
ALTER FUNCTION [sbuser].[sf_MemberHasMedia](@MemberID bigint)
RETURNS INT
AS
BEGIN
DECLARE @OUTSTR INT
DECLARE @OUT1 INT
DECLARE @OUT2 INT
DECLARE @OUT3 INT
SET @OUT1 = (SELECT CAST(COUNT(MemberAudioID) AS BIT)
FROM MemberAudio
WHERE MemberID @MemberID)
SET @OUT2 = (SELECT CAST(COUNT(a.MemberImgID) AS BIT)
FROM MemberImg a
INNER JOIN MemberImgGallery b
ON b.MemberImgGalleryID=a.MemberImgGalleryID
WHERE b.MemberID = @MemberID)
SET @OUT3 = (SELECT CAST(COUNT(MemberVideoID) AS BIT)
FROM MemberVideo
WHERE MemberID = @MemberID)
SET @OUTSTR = @OUT1 + @OUT2 + @OUT3
RETURN @OUTSTR
END
精彩评论