Select len(productid),productid,*
FROM dbo.produts
where Place = 'KA'
and len(productid) <> 10
order by len(productid)
this query filters the data that needs to be updated
-- i need to update the data in 'productid' that is not in the correct format
--(the data should be 10 characters, in 4-2-4 format with leading 0s where they are needed) (productid column is a varchar (256) column)
basically i need to add leading zeros to a varchar column that has a where condition
|productid| |Correct productid value| |
---------------------------------------
|234-55-43||000234-55-43|
|76-7-89||0000076-7-89|
what are the possible solutions for updating these records?
This is very simple, actually:
SELECT productid,
RIGHT('000000000'+productid,10) CorrectProductid
FROM dbo.YourTable
;
If you wanted the corrected format to be in the 4-2-4 format you mentioned:
Using parsename() to parse out the pieces of the string, and right() to add the extra '0's.
select
col
, Corrected = right('0000'+parsename(replace(col,'-','.'),3),4)
+ '-' + right('00'+parsename(replace(col,'-','.'),2),2)
+ '-' + right('0000'+parsename(replace(col,'-','.'),1),4)
from t
where col not like '____-__-____'
rextester demo: http://rextester.com/OXM28014
returns:
+-----------+--------------+
| col | Corrected |
+-----------+--------------+
| 234-55-43 | 0234-55-0043 |
| 76-7-89 | 0076-07-0089 |
+-----------+--------------+
As an update:
update t
set col = right('0000'+parsename(replace(col,'-','.'),3),4)
+ '-' + right('00'+parsename(replace(col,'-','.'),2),2)
+ '-' + right('0000'+parsename(replace(col,'-','.'),1),4)
where col not like '____-__-____'
Related
I have a file with a numeric field, AgentID. I made dummy records. The rows with an AgentID of '0' show up on query
select * from ClaimHistory
where AgentID=' '
I have verified the field is numeric and has a value of zero with ISNUMERIC & ASCII(AgentID)=0
You are experiencing an implicit conversion from string to integer.
An explicit conversion shows that space is being converted to zero.
select cast(' ' as int) as result
+--------+
| result |
+--------+
| 0 |
+--------+
Fiddle
I am working with sku numbers that have the following 9 character structure:
a. a 3 digit number,
b. a period,
c. a five digit number.
An example: 505.12345.
A considerable % of the sku's end in 0. Examples: 505.12340, 505.12300, 505.12000.
I had no trouble keeping the trailing zeroes in SQL Server by setting the datatype to varchar after the migration from S3 -> SQL Server. I used a new machine learning model in AWS Sagemaker that cut off the trailing zeroes prior to the migration to S3.
The example sku's above now look like: 505.1234, 505.123, 505.12
My question: what is the best way to add trailing zeroes to all sku's where LEN([sku]) < 9? I would prefer to keep the sku datatype as varchar.
If you have a string, you can right-pad it with 0s as follows:
left(sku + replicate('0', 9), 9)
Alternatively:
sku + replicate('0', 9 - len(sku))
Demo on DB Fiddle:
select sku,
left(sku + replicate('0', 9), 9) new_sku,
sku + replicate('0', 9 - len(sku)) new_sku2
from (values ('505.1234'), ('505.123'), ('505.12'), ('505.12345')) x(sku)
sku | new_sku | new_sku2
:-------- | :-------- | :--------
505.1234 | 505.12340 | 505.12340
505.123 | 505.12300 | 505.12300
505.12 | 505.12000 | 505.12000
505.12345 | 505.12345 | 505.12345
One simple way would be to CAST back to DECIMAL(9, 5) and then CAST again to CHAR(9)
Data
drop table if exists #tTable;
go
create table #tTable(
dec_num varchar(20) not null);
Insert into #tTable values
('505.1234'),
('505.123'),
('505.12');
Query
select cast(cast(dec_num as decimal(9,5)) as char(9)) char_9
from #tTable;
Output
char_9
505.12340
505.12300
505.12000
I have a column full of duplicate filepaths:
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
I need only the second part of the string ie. C:\298788\DOC1\SUB1\FILE.txt
How do I replace up to the triple backslashes with nothing. I have tried:
UPDATE [TABLE].[dbo].[ColumnName]
SET [ColumnName] = REPLACE([ColumnName], '%\\\', '');
It says all rows updated however nothing has changed. Assuming its something to do with the backslashes.
Using SQL SERVER 2012.
Using stuff()
select col = stuff(col,1,charindex('\\\',col,2)+2,'')
from tbl
rextester demo: http://rextester.com/QRKWP8606
returns:
+------------------------------+
| col |
+------------------------------+
| C:\298788\DOC1\SUB1\FILE.txt |
| C:\298788\DOC1\SUB1\FILE.txt |
| C:\298788\DOC1\SUB1\FILE.txt |
+------------------------------+
as an update:
update tbl
set col = stuff(col,1,charindex('\\\',col,2)+2,'')
where charindex('\\\',col,2)>0
I'm trying to generate a number which will ultimately be stored as string(varchar). e.g.
First - ABC00000001
Second- ABC00000002
.........................
I am able to generate character string as expected. Now the problem is,incremental number.
What i am trying to do is get the last number stored e.g. ABC00000009 and generate the next number that is ABC00000010. How to do the same?
If i extract integers from this than i will get 1 or 10,how to make it according to 8 digit format.
Any help would really be appreciated.
Of course if changing the table structure is not an option, you can try this:
DECLARE #lastValue VARCHAR(15) = 'ABC00000001'
SELECT CONCAT('ABC', RIGHT(100000000 + CAST(RIGHT(#lastValue, 8) AS INT) + 1, 8))
Result
-----------
ABC00000002
I would suggest that you create an identity column. This will increment (usually by 1, but not always). Then create a computed column:
alter table t add generated_number as
('ABC' + right(replicate('0', 8) + cast(idcol as varchar(255)), 8));
Almost the same approach Gordon Linoff has taken, I just prefer to use math where possible instead of string concatenation. My answer is different only because I add id value to 100000000 instead of using replicate.
CREATE TABLE dbo.test (
id int IDENTITY(1, 1) PRIMARY KEY
, some_value sysname UNIQUE
, super_column AS 'ABC' + RIGHT(100000000 + id, 8));
GO
INSERT INTO dbo.test (some_value)
VALUES ('some_value_1'), ('some_value_2');
SELECT *
FROM dbo.test AS T;
Result:
+----+--------------+--------------+
| id | some_value | super_column |
+----+--------------+--------------+
| 1 | some_value_1 | ABC00000001 |
| 2 | some_value_2 | ABC00000002 |
+----+--------------+--------------+
I got a table which contains a column of strings. Those strings are separated by a ;. Now I want to remove the duplicates after the string is splitted. For example:
-----------
| w;w;e;e |
-----------
| q;r;r;q |
-----------
| b;n;n;b |
-----------
The result should be:
-------
| w;e |
-------
| q;r |
-------
| b;n |
-------
Also it should not be a Select function but a (not 100% sure) delete function. So the values in the original table won't be duplicated anymore.
For an update statement, this will de-duplicate your column:
update t
set col = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'');
In sql server 2016, you can use string_split() along with the stuff() with select ... for xml path ('') method of string concatenation to concatenate only distinct values.
select
t.id
, t.col
, dedup = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'')
from t
dbfiddle demo: here
rextester demo: http://rextester.com/MAME55141; this demo uses a CSV Splitter function by Jeff Moden in the absence of string_split().
returns:
+----+---------+-------+
| id | col | dedup |
+----+---------+-------+
| 1 | w;w;e;e | e;w |
| 2 | q;r;r;q | q;r |
| 3 | b;n;n;b | b;n |
+----+---------+-------+
splitting strings reference:
Tally OH! An Improved SQL 8K “CSV Splitter” Function - Jeff Moden
Splitting Strings : A Follow-Up - Aaron Bertrand
Split strings the right way – or the next best way - Aaron Bertrand
string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand
If "e", "r", and "w" are the only values in the string, then the simplest way is to reconstruct the string:
select stuff( (case when string like '%e%' then ';e' else '' end) +
(case when string like '%r%' then ';r' else '' end) +
(case when string like '%w%' then ';w' else '' end),
1, 1, ''
)
I suspect the values might be limited, because these look like file permissions (read/write/execute). Otherwise, you will need to parse the string into separate rows (using XML, a UDF, or a recursive CTE) and recombine the values.
You should learn a lesson here. Don't store lists in strings. These values should either be flags (if I am right about there only being a handful of values). Or, they should be on separate rows of a another table.