I'm trying to add new rows to the existing tables in the database by using table variables. The problem I'm facing is due to the auto-increment primary key in the database. The tables are like below:
Table 1: State
- ID_State(PK)
| state |ID_State |
|-----------|---------|
| Karnataka | 1 |
| Tamil Nadu| 2 |
| UP | 3 |
| . | 4 |
| . | . |
| . | . |
Table 2: City
- ID_city(PK)
| City | ID_City | ID_State|
|-----------|---------|---------|
| Chennai | 1 | 2 |
| Bengaluru | 2 | 1 |
| Lucknow | 3 | 3 |
| Mysore | 4 | 1 |
| . | . | . |
| . | . | . |
Table 3: Location
- ID_Location(PK), ID_City(FK)
| Zip | ID_Location | ID_City |
|------|-------------|---------|
| 0001 | 1 | 1 |
| 0011 | 2 | 2 |
| 0002 | 3 | 1 |
| 0022 | 4 | 2 |
| 0003 | 5 | 1 |
| 0012 | 6 | 2 |
| . | . | . |
| . | . | . |
On the other hand I've the data in an excel sheet that I want to add into the existing database. This is mainly done to add Zip Codes that were missing previously.
Data in Excel sheet:
| Zip | City | State |
|------|-------------|------------------|
| 0001 | Chennai | Tamil Nadu |
| 0002 | Chennai | Tamil Nadu |
| 0003 | Chennai | Tamil Nadu |
| 0004 | Chennai | Tamil Nadu |
| 0005 | Chennai | Tamil Nadu |
| 0011 | Bengaluru | Karnataka |
| 0022 | Bengaluru | Karnataka |
| 0033 | Bengaluru | Karnataka |
| 0044 | Bengaluru | Karnataka |
| 1111 | Lucknow | UP |
| 2222 | Lucknow | UP |
| 3333 | Lucknow | UP |
| . | . | . |
| . | . | . |
Main motto is to add any Zip Code, Cities that are missing in the original database. I've written the following script in which I've made use of table variables.
DECLARE @temp TABLE (Zip_Code NVARCHAR(100) PRIMARY KEY,
City NVARCHAR(100),
State NVARCHAR(100)
)
INSERT INTO @temp (Zip_Code, City, State)
VALUES ('0001', 'Chennai'), ('0002', 'Chennai')
.
.
.
.
select *
from @temp
where City not in (select City from City)
select * from @temp
where Zip not in (select Zip from Location)
These queries return the rows that are not in current database. I need to add them, but do not know how to go about it using table variables. Any help would be much appreciated. Thanks!
P.S: I've implemented this using temporary tables and by adding new columns to the existing tables. In order to make less changes to the existing database, trying to implement using table variables.