jeudi 25 février 2016

Alternative to complex replace() function in SQL Server 2005

I have been asked to do a bit of work on a SQL Server 2005 query that has 26 (!) nested Replace function calls.

There are two issues with this query.

The first is that the 26 replace functions are not enough, a few more are needed, but the query is hitting some size limitations (it's a stored procedure and its making using of sp_MSforEachDB).

The second problem is that the query is just not legible at this stage.

I would like to use table variable with a lookup, but the issue is that the replace query is being used to replace values in one column with values from another column. It does however all work, apparent from not replacing enough strings.

Here is a simplified example to hopefully better explain what I am trying to do.

Table to be converted

ID   MainText                         Ptext1    Ptext2     Ptext3
1    Have a %Ptxt1 %Ptxt2             Apple     Tonight    
2    %Ptxt1 likes %Ptxt2 at %Ptxt3    Sally     Cake       Midnight    

The desired result for 1 is "Have a Apple Tonight", the desired result for 2 is "Sally Likes Cake at Midnight".

The current SQL Looks a bit like

EXEC sp_MSForEachDB 'IF ''?'' LIKE ''%Database%''
Select Replace(Replace(Replace([Maintext], '%Ptxt1' , [Ptext1]),'%Ptxt2',[Ptext2]),'Ptxt3', [Ptext3]) from dbo.mytable  

Please forgive any mistakes in the example.

I have seen nice examples of people using Table variables to store parameters for the replace function - but I haven't seen any where a column reference is used instead of a static string, is this possible ?

Aucun commentaire:

Enregistrer un commentaire