Is there any best way to REPLACE the query?

  • Hi there,

    I have a below query which needs to replace the label to actual value. I can do this by using REPLACE() recursively. Is there any better way to bring the output?

    I'm getting proper output from this query, however I'm curious to find better one. Thanks!

    DECLARE @a AS VARCHAR(1000)

    SET @a = 'This is <<FirstName>> <<LastName>> FROM <<PLACE>>, MY DOB IS ON <<DATE>> at <<TIME>>. THANKS'

    SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@A,'<<FirstName>>','LOKESH'),'<<LastName>>','GOWDA'),'<<PLACE>>','MANGALORE'),'<<DATE>>','2000-FEB-09'),'<<TIME>>','09:20pm')

    Regards,

    Lokesh GB

  • Nested REPLACE is very efficient, so there will not be a faster way.

  • Thanks dude 🙂

  • Using Replace is good logic and it will be faster

  • laurie-789651 (9/26/2012)


    Nested REPLACE is very efficient, so there will not be a faster way.

    There's nearly always a faster way:

    DECLARE @a AS VARCHAR(1000)

    SET @a = 'This is <<FirstName>> <<LastName>> FROM <<PLACE>>, MY DOB IS ON <<DATE>> at <<TIME>>. THANKS'

    SELECT REPLACE(

    REPLACE(

    REPLACE(

    REPLACE(

    REPLACE(@A COLLATE Latin1_general_bin

    ,'<<FirstName>>','LOKESH'),'<<LastName>>','GOWDA'),'<<PLACE>>','MANGALORE'),'<<DATE>>','2000-FEB-09'),'<<TIME>>','09:20pm')

    Explanation of how REPLACE is slow when using non-binary collations: http://connect.microsoft.com/SQLServer/feedback/details/512459/replace-function-extremely-slow-with-non-binary-windows-collation


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply