Sql query to add Zero between string with character and digits - sql

What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675 should turn into QTX0023675
UPDATE Table
SET QID = 'QTX0023675'
WHERE QID='QTX23675';
There are many records to update and i found query with leading zeros.
Tried with spliting the string.

In most databases, you could do something like this:
UPDATE Table
SET QID = CONCAT(LEFT('QTX0023675', 3), '00', RIGHT('QTX0023675', 5))
WHERE QID LIKE '________';
In any given database, there might be somewhat simpler methods, but the idea is the same.

Try This to make the result Dynamic
WITH CTE
AS
(
SELECT Val = 'XTP231'
)
SELECT
*,
NewVal = SUBSTRING(Val,1,PATINDEX('%[0-9]%',Val)-1)+'00'+SUBSTRING(Val,PATINDEX('%[0-9]%',Val),LEN(Val))
FROM CTE
THe Output is as follows

UPDATE TABLE SET QID= STUFF(QID,PATINDEX('%[0-9]%',QID),0,'00')

Related

SQL Query to compare the first X characters of 2 fields in a table

Say I have a table named 'Parts'. I am looking to create a SQL query that compares the first X characters of two of the fields, let's call them 'PartNum1' and 'PartNum2'. For example, I would like to return all records from 'Parts' where the first 6 characters of 'PartNum1' equals the first 6 characters of 'PartNum2'.
Parts
PartNum1
PartNum2
12345678
12345600
12388888
12345000
12000000
14500000
the query would only return row 1 since the first 6 characters match. MS SQL Server 2017 in case that makes a difference.
If they are strings, use left():
left(partnum1, 6) = left(partnum2, 6)
This would be appropriate in a where, on, or case expression. Note that using left() would generally prevent the use of indexes. If this is for a join and you care about performance, you might want to include a computed column with the first six characters.
you can try something like this. I am assuming datatype as integer. You can set size of varchar based on length of fields.
select *
from Parts
WHERE SUBSTRING(CAST(PartNum1 AS VARCHAR(max)), 1,6) = SUBSTRING(CAST(PartNum2 AS VARCHAR(max)), 1,6)
You can go for simple division to see if the numerator matches for those partnumbers.
DECLARE #table table(partnum int, partnum2 int)
insert into #table values
(12345678, 12345600)
,(12388888, 12345000)
,(12000000, 14500000);
select * from #table where partnum/100 = partnum2/100
partnum
partnum2
12345678
12345600

How to replace the first letter of a string using SQL and Postgres?

I have a database column of varchar(191) with strings in the database. We need to replace the first letter of every string with an "E". So for instance, we have:
Cuohvi-AQNqalPq8zdr1cOA
Needs to be changed to
Euohvi-AQNqalPq8zdr1cOA
Do you know how we can achieve this in Postgres with a SQL query? It needs to be updated for the whole table.
Per docs use overlay():
UPDATE the_table SET the_field = overlay(the_field placing 'E' from 1 for 1);
Use a combination of the CONCAT function and the RIGHT function with an argument of -1.
SELECT CONCAT('E', RIGHT('Cuohvi-AQNqalPq8zdr1cOA', - 1))
FROM yourtable
SELECT CONCAT('E', RIGHT(yourfield, - 1))
FROM yourtable
dbfiddle: https://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=e198b05f02283137afc39c24bb6c788d

SQL Server: How to select rows which contain value comprising of only one digit

I am trying to write a SQL query that only returns rows where a specific column (let's say 'amount' column) contains numbers comprising of only one digit, e.g. only '1's (1111111...) or only '2's (2222222...), etc.
In addition, 'amount' column contains numbers with decimal points as well and these kind of values should also be returned, e.g. 1111.11, 2222.22, etc
If you want to make the query generic that you don't have to specify each possible digit you could change the where to the following:
WHERE LEN(REPLACE(REPLACE(amount,LEFT(amount,1),''),'.','') = 0
This will always use the first digit as comparison for the rest of the string
If you are using SQL Server, then you can try this script:
SELECT *
FROM (
SELECT CAST(amount AS VARCHAR(30)) AS amount
FROM TableName
)t
WHERE LEN(REPLACE(REPLACE(amount,'1',''),'.','') = 0 OR
LEN(REPLACE(REPLACE(amount,'2',''),'.','') = 0
I tried like this in place of 1111111 replace with column name:
Select replace(Str(1111111, 12, 2),0,left(11111,1))

Make column values in a table have equal number of characters

I have a table DomainDetail having a column fieldID.
It has values like A1,B22,A567,D7779,B86759 .. i.e. from two characters to max six characters.
I want these values have equal number of characters
A000001,B000022,A000567,D07779 and B86759 .
This is how I think I should proceed
Estimate size of field value = LEN(fieldID)
Insert number of zeros equal to (6 - number of characters) .
How can I insert 0's sandwiched inside original value . How can do in SQL ?
like this
select
left(fieldID, 1) +
right('000000' + right(fieldID, len(fieldID) - 1), 5)
from DomainDetail
take a look at SQL FIDDLE example
It sounds like a problem better solved by business logic, i.e. the layer of code above your database. Whenever you insert, do the padding in that code - then always use that code/layer to insert into the table.
It seems to be a business logic requirement anyway - "ID must have a maximum 6 characters". Because a database wouldn't impose such a limit.
(unless you are using stored procedures as your business logic layer? in which case, PadLeft function in T-SQL)
select
stuff(fieldId,2,0,
LEFT('0000000000000000000000000',
(select max(LEN(FieldID)) from DomainDetail)
-LEN(fieldId)))
from DomainDetail
If you need a fixed output length just replace inner select (select max(LEN(FieldID)) from DomainDetail) with for example 6
Here is a SQLFiddle demo
If you want to UPDATE, then use this
UPDATE DomainDetail
SET fieldId=
SUBSTRING(fieldId,1,1)+
REPLICATE('0',6-LEN(id))+
SUBSTRING(fieldId,2,LEN(id)-1)
If you want to just SELECT without altering the values in the table, then this should work
SELECT SUBSTRING(id,1,1)+
REPLICATE('0',6-LEN(id))+
SUBSTRING(id,2,LEN(id)-1)
FROM DomainDetail
Hope this helps,
Raj
select stuff(fieldid, 2, 0, replicate('0', 6-len(fieldid)))
from DomainDetail

insert substring into new column

I have a db where one column contains 2 pieces of data, e.g. first and last name.
The format is roughly ABC-1D23-4F34
I want to copy and insert the first 3 letters, the ABC, into a new column. Lets call these columns [full_id] and [ref_id]
From reading it looks like substring is able to do this but I am doing something wrong here.
INSERT INTO [ref_id]
SUBSTRING([full_id], 1, 3)
FROM db.Name
Thank you for the help.
EDIT:
The update string worked. But I found that there are issues with my data and it is not all in proper formatting.
Is there a way to write a case where if the substring is not 3 letters it writes a null value?
Thanks again, and sorry for having bad data.
Try
UPDATE Name
SET ref_id = CASE WHEN CHARINDEX('-',full_id) = 4 THEN SUBSTRING(full_id,1,3) ELSE NULL END
That will set the ref_id column for all rows using the first 3 characters of the full_id column.
If it is a column in the same table you need to switch to an update statement.
UPDATE db.Name SET [ref_id] = SUBSTRING([full_id], 1, 3)
Perhaps you want something like:
Update db.Name set ref_id = substring([full_id], 1,3)