Hi, I am trying to check the data in a column that is like ABC*1234 and expand it to look like ABC000001234.
I am new to sql and have basis experience.
Thanks
Dave
April 22, 2020 at 2:49 pm
What is the requirement exactly?
Is it as simple as replacing an asterisk with five zeros, or do you want something which fills out the numeric part with leading zeros, to make it nine characters long, or something else?
April 22, 2020 at 2:53 pm
Hi,
The asterisk could represent 1 or more characters and I need to expand all of the entries in that column that are like the above to 12 characters, by padding the centre with zeros.
April 22, 2020 at 2:56 pm
SELECT REPLACE('ABC*1234','*','00000') newvalue
April 22, 2020 at 3:06 pm
SELECT REPLACE(oldvalue,'*', replicate('0', 12 - len(t.oldvalue) + 1)) newvalue
from (values
('ABC*1')
,('ABC*123')
,('ABC*12345')
,('ABC*1234567')
,('ABC*12345678')
,('ABC12345678')
) t(oldvalue)
April 22, 2020 at 3:11 pm
REPLACE(data_column, '*', ISNULL(REPLICATE('0', 12 - (LEN(data_column) - 1)), ''))
Some examples:
SELECT data_column,
REPLACE(data_column, '*', ISNULL(REPLICATE('0', 12 - (LEN(data_column) - 1)), '')) AS new_data
FROM ( VALUES('ABC*1234'),('BC*234'),('CDEFG*1'),('D*23456789012') ) AS test_data(data_column)
SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".
April 22, 2020 at 4:23 pm
Scott,
I have run your code and it does what I require, as an addition how would I iterate through all records in the table checking the column and update to the new data value?
Thanks
Dave
UPDATE dbo.table_name
SET data_column = REPLACE(data_column, '*', ISNULL(REPLICATE('0', 12 - (LEN(data_column) - 1)), ''))
WHERE (LEN(data_column_name) < 12 OR LEN(data_column_name) = 13) AND
(data_column LIKE '%*%')
SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".
Viewing 8 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply