• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 66
  • Last Modified:

sql user Function to get list of values

Here is some sample data from my table named campaignoffers
(the fields are True or False to indicate whether an offer is valid for a given campaign)

campaignid      FreeCash          Points          GiftCard      Food      

236                         F                            F                F               F      
244                        T                            F                 F               F
249                        F                           T                     T              F      

I would like to write a function that will look at the individual flags and return a comma separated list of valid offers
(taking in campaign id as input parameter)

There should be at least one flag set to T for each campaign but if for some reason there isn't I want the function to return the string
'No Valid Offers'

Given the sample data above, I would like it to return the following

  'No Valid Offers' ( for campaign id  236)

'Free cash' ( for campaign id  244)

'Points, Gift Card'  ( for campaign id  249)
0
johnnyg123
Asked:
johnnyg123
2 Solutions
 
Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
Does this help? It's a quick approach that came to my mind - I have created a scalar valued function which implements UNPIVOT and subsequent string concatenation.

USE tempdb;
GO

IF OBJECT_ID('dbo.OffersByCampaign','U') IS NOT NULL
    DROP TABLE dbo.OffersByCampaign;
GO

IF OBJECT_ID('dbo.func_GetOffersByCampaign') IS NOT NULL
    DROP FUNCTION dbo.func_GetOffersByCampaign;
GO 

--Table & data for demo purposes only. 
--Please use actual tables/columns in your query
CREATE TABLE dbo.OffersByCampaign (CampaignId INT     NOT NULL,
                                   FreeCash   CHAR(1) NOT NULL,
                                   Points     CHAR(1) NOT NULL,
                                   GiftCard   CHAR(1) NOT NULL,
                                   Food       CHAR(1) NOT NULL
                                  );
GO

--Insert Test data
INSERT INTO dbo.OffersByCampaign (CampaignId, FreeCash, Points, GiftCard, Food)
VALUES (236, 'F', 'F', 'F', 'F'),
       (244, 'T', 'F', 'F', 'F'),
       (249, 'F', 'T', 'T', 'F');
GO


CREATE FUNCTION dbo.func_GetOffersByCampaign (@CampaignId INT)
    RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @offersByCampaign VARCHAR(MAX) = NULL;

    ;WITH OffersCTE (CampaignId, OfferEligibility, Offer)
    AS (SELECT Unpivoted.CampaignId, 
               Unpivoted.OfferEligibility, 
               Unpivoted.Offer
        FROM (SELECT oc.CampaignId, oc.FreeCash, oc.Points, oc.GiftCard, oc.Food
              FROM dbo.OffersByCampaign AS oc
              WHERE oc.CampaignId = @CampaignId
             ) AS UnPvt
        UNPIVOT (OfferEligibility FOR Offer IN (FreeCash, Points, GiftCard, Food)) AS Unpivoted
       )
    SELECT @offersByCampaign = COALESCE(@offersByCampaign + ', ','') + ofCTE.Offer
    FROM OffersCTE AS ofCTE
    WHERE ofCTE.OfferEligibility = 'T'

    RETURN ISNULL(@offersByCampaign,'No Valid Offers');
END
GO

SELECT oc.CampaignId, 
       oc.FreeCash, 
       oc.Points,
       oc.GiftCard,
       oc.Food,
       dbo.func_GetOffersByCampaign (oc.CampaignId) AS ConcatenatedOffers
FROM dbo.OffersByCampaign AS oc;
GO

/* RESULTS
CampaignId  FreeCash Points GiftCard Food ConcatenatedOffers
----------- -------- ------ -------- ---- -------------------
236         F        F      F        F    No Valid Offers
244         T        F      F        F    FreeCash
249         F        T      T        F    Points, GiftCard
*/

Open in new window

0
 
Scott PletcherSenior DBACommented:
For best overall performance, a table-valued function is best.  First I'll show the code to invoke the function, then the function code itself:

SELECT co.*, gvo.*
FROM dbo.campaignoffers co
CROSS APPLY dbo.GetValidOffers ( co.campaignid ) gvo


/* these SETings ARE important, don't leave out*/
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE FUNCTION dbo.GetValidOffers
(
    @campaignId int
)
RETURNS TABLE
AS
RETURN (
SELECT
    ISNULL(NULLIF(STUFF(
    CASE WHEN FreeCash = 'T' THEN CAST(', FreeCash' AS varchar(100)) ELSE '' END +
    CASE WHEN Points = 'T' THEN CAST(', Points' AS varchar(100)) ELSE '' END +
    CASE WHEN GiftCard = 'T' THEN CAST(', GiftCard' AS varchar(100)) ELSE '' END +
    CASE WHEN Food = 'T' THEN CAST(', Food' AS varchar(100)) ELSE '' END
    , 1, 2, ''), ''), 'No Valid Offers') AS ValidOffers
FROM dbo.campaignoffers
WHERE campaignid = @campaignId
)
GO
0
 
johnnyg123Author Commented:
Thanks so much for the responses!

I elected to go with scott's solution because of the performance and cleaner approach

I did want to give Nakul some points for taking the time to post a working solution as well
1

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now