I have an NVARCHAR(10) column in a table. It can store any UNICODE string.
I want to replace every char that differs from "1" with "0".
Say I have the line '012345C18 *'. I have to get "0100000100".
I managed to do this using an auxiliary table that contains indices from 1 to the size of my column (10), for example:
CREATE TABLE HELP(Idx INT) INSERT INTO HELP SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 DECLARE @myStr VARCHAR(10) SET @myStr = '012345C18*' SELECT STUFF((SELECT '' + CASE(B.Ch) WHEN '1' THEN '1' ELSE '0' END FROM ( SELECT SUBSTRING(A.Val,H.Idx,1) AS Ch FROM (SELECT @myStr AS Val) A CROSS JOIN HELP H )B FOR XML PATH('')),1,0,'')
It works, but can it be done better? This seems ugly for a simple update, ignoring the fact that the size of the column may change over time. It should also work on SQL> = 2005 .
SQL feed here
Thanks!
source share