I have a NVARCHAR(10)
column in a table. It can store any type of UNICODE strings.
I want to replace every char which is different than '1' with '0'.
Let's say I have the string '012345C18*'. I should get '0100000100'.
I managed to do it using a helper table which contains indexes from 1 to the size of my column (10), like this:
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 in a nicer way? This seems ugly for a simple update, ignoring the fact that the size of the column can change over time. It also has to run on SQL >=2005.
SQL Fiddle here
Thanks!