Technical Article

Dynamically Generating HTML Tags from T-SQL

,

Here's a real-life challenge I was faced with at work: my company (a talent agency) needed me to create a report listing all of our actors that we represent - and for each actor, a comma-delimited string of each production that they've starred in.  Simple enough, right......except that, within the comma-delimited list of productions, they wanted those productions that were "theatre" productions to be shown in italics!

Luckily, the front-end tool that would display the data was HTML-aware.  So, the challenge became, "How do I dynamically generate the appropriate HTML tags around each item in the list that's in the theatre category?"

Below is the code I came up with to do this.  Of course, I have simplified it greatly, and am using some "dummy" tables in this example,  But at least you can get the concept from the example below.  (Note: this uses a UDF, so it will only work in SQL 2000.  If you're using version 7, you must extract the code and run it as straght SQL).

CREATE TABLE Actors
(
ActorID INT PRIMARY KEY,
ActorName VARCHAR(200)
)
GO
CREATE TABLE ProductionTypeLU
(
ProductionTypeLUID INT PRIMARY KEY,
ProductionTypeString VARCHAR(100)
)
GO
CREATE TABLE Productions
(
ProductionID INT PRIMARY KEY,
Title VARCHAR(200),
ProductionType INT REFERENCES ProductionTypeLU(ProductionTypeLUID)
)
GO
CREATE TABLE ActorProductions
(
ActorProductionID INT PRIMARY KEY,
ActorID INT REFERENCES Actors(ActorID),
ProductionID INT REFERENCES Productions(ProductionID)
)
GO

INSERT Actors
SELECT 1, 'Bob' UNION SELECT 2, 'Jim' UNION SELECT 3, 'Jane'
GO
INSERT ProductionTypeLU
SELECT 1, 'Motion Picture' UNION SELECT 2, 'Television' UNION SELECT 3, 'Theatre'
GO
INSERT Productions
SELECT 1, 'My Film', 1 UNION SELECT 2, 'My TV', 2 UNION SELECT 3, 'My Theatre', 3
GO
INSERT ActorProductions
SELECT 1, 1, 1 UNION SELECT 2, 2, 2 UNION SELECT 3, 3, 3
UNION SELECT 4, 1, 2  UNION SELECT 5, 1, 3
GO

CREATE FUNCTION GetProductions(@ActorID int)
RETURNS VARCHAR(1000)

AS
BEGIN

DECLARE @Prod VARCHAR(1000)

SELECT @Prod = ISNULL(@Prod + ', ', '') + 
CASE p.ProductionType
/*Here's where we generate the tags*/WHEN 3 THEN '<I>' + p.Title + '</I>'
ELSE p.Title
END
FROM ActorProductions ap
JOIN Productions p
ON ap.ProductionID = p.ProductionID
WHERE ap.ActorID = @ActorID

RETURN(@Prod)

END

GO

SELECT ActorName, dbo.GetProductions(ActorID) as Credits
FROM Actors

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating