0

We have a MS SQL database that holds HTML markup. However, we need to frequently change the CSS declarations at the top. Is there a way to write a SQL query that would allow us to easily replace everything between the tags? For example:

replace '<style>OLDSTYLES</style>' with '<style>NEWSTYLES</style>'

More specifically - can we use a dynamic variable in place of "OLDSTYLES" so that we don't have to copy+paste the old css in each time?

3
  • 1
    I have to ask, can't you just use a stylesheet file? Commented Oct 4, 2011 at 15:27
  • 1
    Why are you storing this multiple times? Can't you just store it in one place and add the styles in when outputting it? Commented Oct 4, 2011 at 15:27
  • Great questions - i agree external CSS or a single storage location is ideal. However, for internal business reasons, we are unable to do that at this time. This is a temporary workaround. Commented Oct 4, 2011 at 15:42

4 Answers 4

2

If HTML markup is a well formed XML and you are familiar with XPath, then you might try the following solution. It should work for the case you specified (the style tag), but if you need to modify another tag, you need to change XPath expression accordingly, which here is "(/html/style/text())[1]". For more details: XML data modification with XQuery at MSDN.

-- sample data
declare @data table
(
    html xml
)
insert into @data select '<html><style>oldstyle</style><body></body></html>'

-- solution
declare @replacement varchar(50)
set @replacement = 'newstyle'

update @data
set html.modify('replace value of (/html/style/text())[1] with sql:variable("@replacement")')

select * from @data
Sign up to request clarification or add additional context in comments.

Comments

1

This should work fine, it might need a little tweaking but it does the trick:

DECLARE
    @markup NVARCHAR(MAX)
    ,@OldStyles NVARCHAR(MAX)
    ,@NewStyles NVARCHAR(MAX)
    ,@PatIndex INT

SELECT @markup = '<style>OLDSTYLES</style>'
       ,@OldStyles = 'OLDSTYLES'
       ,@NewStyles = 'NewStyles'

SET @PatIndex = PATINDEX('%<style>%',@markup)

IF @PatIndex > 0
SET @markup = REPLACE(@markup,@OldStyles,@NewStyles)

SELECT @markup

Comments

0

Don't hard-code (inline) the styles. Use a stylesheet and class names.

1 Comment

Not an answer to the question and not suitable for all scenarios. e.g. HTML emails.
0

What you want to do is link to an external stylesheet.

If that won't work, then put some sort of keystring (such as "OLDSTYLES") there, and replace it after you take the html out of the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.