I'm having 3 small queries where I would like to get the top 1 row.Problem is that the queries are some kind of ranking based upon a count and order by (besides the top 1).I tried to write a function that would return the value needed, but that doesn't seem to work. The function:ALTER FUNCTION [dbo].[BC_getCustomerFavorites]( -- Add the parameters for the function here @CustomerId Bigint, @TypeId TinyInt) RETURNS Nvarchar(75)ASBEGIN -- Declare the return variable here DECLARE @Returnstring nvarchar(75) DECLARE @Description as nvarchar(75) Declare @Type as char(10) Declare @Count as int SET @returnstring = '' -- Add the T-SQL statements to compute the return value here IF @TypeId = 1 -- select favorite book select @returnstring = top 1 productid from tblBC_CustomerProducts c where c.customerid = @CustomerId AND c.typeid= 1 IF @TypeId = 2 -- select favorite genre select @returnstring = top 1 p.numeriek1 from tblBC_CustomerProducts c INNER JOIN tblProduct p ON c.productid = p.productid where c.customerid = @CustomerID AND c.typeid= 2 group by p.numeriek1 order by count(*) DESC, newid() IF @TypeId = 3 -- select favorite author select @returnstring = top 1 p.text1 from tblBC_CustomerProducts c INNER JOIN tblProduct p ON c.productid = p.productid where c.customerid = @CustomerID AND c.typeid= 2 group by p.text1 order by count(*) DESC, newid() -- Return the result of the function RETURN @returnstringEND
Problems with the function are that top 1 seems unsupported, newid() seems unsupported and are the IF's supported in fuctions?As an alternative I tried to write a SP that would return three rows (one for each query) but the SP uses UNIONS that seem to get bugged by the order by clauses:LTER PROCEDURE [dbo].[BC_getFavoriteBook] -- Add the parameters for the stored procedure here @CustomerId BigintASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- select favorite book select top 1 productid as Description, 'book' as Type, 1 as Count from tblBC_CustomerProducts c where c.customerid = @CustomerId AND c.typeid= 1 -- select favorite genre UNION ALL select top 1 p.numeriek1 as Description, 'genre' as Type, count(*) as Count from tblBC_CustomerProducts c INNER JOIN tblProduct p ON c.productid = p.productid where c.customerid = @CustomerID AND c.typeid= 2 group by p.numeriek1 order by count(*) DESC, newid() -- select favorite author UNION ALL select top 1 p.text1 as Description, 'author' as Type, count(*) as Count from tblBC_CustomerProducts c INNER JOIN tblProduct p ON c.productid = p.productid where c.customerid = @CustomerID AND c.typeid= 2 group by p.text1 order by count(*) DESC, newid()END
Any chances on getting the function or the SP to work with these queries. Or should I use seperate queries (sp) for all three ?The queries self are fine, i've tested them and the returned results are correct.