I have two tables, both with columns ID_Number and version. However, the format of the ID_number is different. My goal is to compare the two tables and output any rows with the same ID_number but different versions.
The format difference is as follows:
Eg. ID number in first table is "23-4567". The corresponding ID number in the second table is "1023004567". "10" is added before the "23" and "-" is replaced with "00". It's the same for all the IDs.
First, I used "substring" to make the ID_Number from table1 to match with ID_Number from table2 and rename this new column as newIDNumber(table1), and compare newIDNumber(table1) with ID_Number(table2). The code to convert ID_Number in table1 for the above example is as such,
Eg. '10' + SUBSTRING(@ID_number, 1, 2) + '00' + SUBSTRING(@ID_number, 4,4) AS newIDNumber
Now I write the following code to check the version difference
SELECT ID_Number, version, "10" + SUBSTRING(@ID_number, 1, 2) + "00" + SUBSTRING(@ID_number, 4,4) (From first table) AS newIDNumber
FROM table1
WHERE (NOT EXISTS
(SELECT ID_Number, version
FROM table2
WHERE (table1.newIDNumber= table2.ID_Number) AND (table1.version = table2.version)
)
)
It outputs an error saying "Unknown column 'table1.newIDNumber' in 'where clause'". How am I able to do compare without disrupting the database (inserting newIDNumber column to table1)?
Would "declare newIDNumber" work?
SELECT
ID_Number
, version
FROM
table1
WHERE
NOT EXISTS
(
SELECT 1
FROM table2
WHERE
"10" + SUBSTRING(table1.ID_number, 1, 2)
+ "00" + SUBSTRING(table1.ID_number, 4,4) = table2.ID_Number
AND table1.version = table2.version
)
you should throw some sample data .
Try this,
declare @t table(col1 varchar(50))
insert into @t values('23-4567')
declare @t1 table(col1 varchar(50))
insert into @t1 values('1023004567')
;With CTE as
(
select t.col1
from @t t
inner join @t1 t1
on substring(t.col1,1,charindex('-',t.col1)-1)=
substring(t1.col1,charindex('10',t1.col1)+2,charindex('00',t1.col1)-3)
where NOT EXISTS(
select * from @t1 t1
where substring(t.col1,charindex('-',t.col1)+1,len(col1))
=substring(t1.col1,charindex('00',t1.col1)+2,len(col1))
)
)
select * from cte t
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.