If I have an address table and a cities lookup table and the address table has the cities in text instead of a foreign key, how would I replace the text with its counterpart in the lookup table?
Example:
Table luCities:
ID Name
--------------------
1 New Orleans
2 Portland
3 Seattle
Table Addresses:
ID Street City State Zip
--------------------------------------------------
1 123 main st. New Orleans OR 96556
should become
ID Street CityId State Zip
--------------------------------------------------
1 123 main st. 1 OR 96556
I have roughly 250 rows to match multiple cities with, so I'm hoping that a single UPDATE/SET statement can be used to match and modify them.
I believe you are looking for an update-join. If you add CityID to addresses as a FK to luCities, you can run this:
UPDATE Addresses SET
CityID = c.ID
FROM Addresses A
inner join luCities C on A.City = C.Name
Once everything looks correct, you can drop the old City column if you like.
Related
I have a table called Customer that has several columns called National Code and Name. It also has a number of other features called Contact Numbers and Recommenders, since the number of Contact Numbers and Recommenders is more than one, so you need some other table to store them.
Also suppose I have other tables like the Customer, each of which has a number of attributes greater than one.
What is your suggestion for storing these values?
In one source, it was suggested that for each table, a table called StringValue be used for storage. Does EF core have a way to implement StringValue without writing additional code?
Example:
Customer Table:
CustomerId Name NationalCode
------------------------------------------------------------------------
1 David xxxx
------------------------------------------------------------------------
StringValue Table:
StringId CustomerId StringName Value
------------------------------------------------------------------------
10 1 PhoneNumber 915245
11 1 PhoneNumber 985452
12 1 PhoneNumber 935446
13 1 Recommenders Mr Jhon
14 1 Recommenders Mr bb
------------------------------------------------------------------------
I think it is more intutive create a new table for the field which has more than one records, then configure a one-to-many relationship between the two tables. Take your case as an example, you can divide the customer table into three tables, they can be linked by foreignkey:
1.Customer Table:
CustomerId Name NationalCode
---------------------------------------------
1 David xxxx
2.Contact Table:
Id CustomerId PhoneNumber
---------------------------------------------
1 1 915245
2 1 985452
3 1 935446
3.Recommender Table:
Id CustomerId RecommenderName
---------------------------------------------
1 1 Mr Jhon
2 1 Mr bb
I'm using SQL Server 2017 and I've been trying to figure this out for hours. My goal is to compare 2 tables and only insert NEW rows based on UNIQUE cells. All the columns have an ID number, but I have not assigned a primary key. My goal is to ONLY add extra rows containing UNIQUE cells if none of the criteria match. This is how my tables are setup now.
Old-Data (Table name is Test1)
FName LNname Address City State Zipcode Phone Phone2 ID
Frank Smith 444 Main Y'all TX 77484 281-788-9898 NULL 1
Thomas Parker 343 Tire Y'all TX 77484 281-788-5453 NULL 2
Ben Krull 232 Wheel Y'all TX 77484 281-788-9535 NULL 3
New-Data (Table name is Test2)
FName LNname Address City State Zipcode Phone Phone2 ID
Frank Smith 444 Main Y'all TX 77484 281-788-9898 NULL 1
Thomas Parker 343 Tire Y'all TX 77484 281-788-5453 NULL 2
Ben Krull 232 Wheel Y'all TX 77484 281-788-9535 NULL 3
Juan Roberto 444 Gas Y'all TX 77484 281-788-3434 NULL 4
Ben Krull 232 Wheel Y'all TX 77484 281-788-9535 713-545-4353 5
As you can see, ID's 1,2 and 3 are identical in both tables. ID-4 is a completely unique row, as is ID-5 because of the Phone2 entry. I found some code and modified it a bit to match the headers I care about it to help me determine what entries are duplicates or not. This is the code that has been driving me crazy.
INSERT TEST1 (Name
,Last_Name
,Address
,City
,State
,Zip_Code
,Phone
,Phone2
)
SELECT Name
,Last_Name
,Address
,City
,State
,Zip_Code
,Phone
,Phone2
FROM TEST2
WHERE TEST2.NAME not in (select Name from test1)
AND TEST2.Address not in (select Address from test1)
AND TEST2.City not in (select City from test1)
AND TEST2.State not in (select State from test1)
AND TEST2.Zip_Code not in (select Zip_Code from test1)
AND TEST2.Phone not in (select Phone from test1)
AND TEST2.Phone2 not in (select phone2 from test1)
I'm trying to match all the fields and if a unique CELL is found the new row is entered into the old_data table. I see no errors after executing it, but nothing happens too. Interestingly enough, If I remove all the code below the line that says, "WHERE TEST2.NAME not in (select Name from test1)" ID-4 (Juan Roberto) is transferred over, but nothing happens with ID-5.
I'm really starting to think WHERE cannot be used to compare the duplicates and modify or add entries, but I could be wrong. A merge feature would be awesome, but I'm happy with just the former since I could always run a different script to clean up the table for dupes. I'm hoping somebody might be able to point me in the right direction since I've got millions of rows in different tables that need to be compared and trimmed down. Thanks.
Just try the following code, I am not sure about it will work for you, because I am not tested it
SELECT * INTO #TEMP FROM Test2(NOLOCK);
DELETE #TEMP
FROM #TEMP
INNER JOIN Test1
ON #TEMP.NAME = Test1.NAME
AND #TEMP.Address = Test1.Address
AND #TEMP.City = Test1.City
AND #TEMP.State = Test1.State
AND #TEMP.Zip_Code = Test1.Zip_Code
AND #TEMP.Phone = Test1.Phone
AND #TEMP.Phone2 = Test1.Phone2 ;
INSERT INTO Test1
SELECT * FROM #TEMP;
The short version is I'm trying to map from a flat table to a new set of tables with a stored procedure.
The long version: I want to SELECT records from an existing table, and then for each record INSERT into a new set of tables (most columns will go into one table, but some will go to others and be related back to this new table).
I'm a little new to stored procedures and T-SQL. I haven't been able to find anything particularly clear on this subject.
It would appear I want to something along the lines of
INSERT INTO [dbo].[MyNewTable] (col1, col2, col3)
SELECT
OldCol1, OldCol2, OldCol3
FROM
[dbo].[MyOldTable]
But I'm uncertain how to get that to save related records since I'm splitting it into multiple tables. I'll also need to manipulate some of the data from the old columns before it will fit into the new columns.
Thanks
Example data
MyOldTable
Id | Year | Make | Model | Customer Name
572 | 2001 | Ford | Focus | Bobby Smith
782 | 2015 | Ford | Mustang | Bobby Smith
Into (with no worries about duplicate customers or retaining old Ids):
MyNewCarTable
Id | Year | Make | Model
1 | 2001 | Ford | Focus
2 | 2015 | Ford | Mustang
MyNewCustomerTable
Id | FirstName | LastName | CarId
1 | Bobby | Smith | 1
2 | Bobby | Smith | 2
I would say you have your OldTable Id to preserve in new table till you process data.
I assume you create an Identity column Id on your MyNewCarTable
INSERT INTO MyNewCarTable (OldId, Year, Make, Model)
SELECT Id, Year, Make, Model FROM MyOldTable
Then, join the new table and above table to insert into your second table. I assume your MyNewCustomerTable also has Id column with Identity enabled.
INSERT INTO MyNewCustomerTable (CustomerName, CarId)
SELECT CustomerName, new.Id
FROM MyOldTable old
JOIN MyNewCarTable new ON old.Id = new.OldId
Note: I have not applied Split of Customer Name to First Name and
Last Name as I was unsure about existing data.
If you don't want your OldId in MyNewCarTable, you can DELETE it
ALTER TABLE MyNewCarTable DROP COLUMN OldId
You are missing a step in your normalization. You do not need to duplicate your customer information per vehicle. You need three tables for 4th Normal form. This will reduce storage size and more importantly allow an update to the customer data to take place in one location.
Customer
CustomerID
FirstName
LastName
Car
CarID
Make
Model
Year
CustomerCar
CustomerCarID
CarID
CustomerID
DatePurchaed
This way you can have multiple owners per car, multiple cars per owner and only one record needs to be updated per car and or customer...4th Normal Form.
If I am reading this correctly, you want to take each row from table 1, and create a new record into table A using some of that row data, and then data from the same original row into Table B, Table C but referencing back to Table A again?
If that's the case, you will create TableA with an Identity and make thats the PK.
Insert the required column data into that table and use the #IDENTITY to retrieve the last identity value, then you will insert the remaining data from the original table into the other tables, TableB, TableC, etc. and use the identity you retrieved from TableA as the FK in the other tables.
By Example:
Table 1 has columns col1, col2, col3, col4, col5
Table A has TabAID, col1, col2
Table B has TabBID, TabAID, col3
TableC has TabCID, TabAID, col4
When the first row is read, the values for col1 & col2 are inserted into TableA.
The Identity is captured from that row inserted, and then value for col3 AND the identity are entered into TableB, and then value for col4 AND the identity are entered into TableC.
This is a standard data migration technique for normalizing data.
Hope this assists,
I have an employee table with multiple entries for the same person.
Using their SIN number you are able to determine if they are the same person.
Example:
Id Name SIN
1 John Smith 1234
2 John Smith 1234
3 Jess Jones 4321
I want to be able to copy everyone in this table, into a new table.
I want to create a new column (UserKey [GUID]) that is unique to the user who is in the table multiple times.
I want to use this new UserKey [GUID] instead of the SIN number.
Example:
Id Name UserKey (Guid)
1 John Smith 1234DFKJ2328LJFD
2 John Smith 1234DFKJ2328LJFD
3 Jess Jones 9543SLDFJ28EKJFF
I have no idea on how to approach this query. Any help would be great.
I am using MS SQL Server 2008.
Thanks.
You can just create a temp table, mapping SIN to a new GUID. Then you can join the original table with the mapping table, and create the new table from that.
# Create a table called #temp with the mappings SID => new GUID
SELECT SIN, newid() UserKey INTO #temp FROM (SELECT DISTINCT SIN FROM Table1) a
# ...and join that and the original table to a new table.
SELECT id, name, userkey
INTO NewTable
FROM Table1 t1
JOIN #temp t2
ON t1.SIN = t2.SIN
SQLFiddle here.
An application I am developing needs to provide access to data based on a list of cities defined for each client. A client can have:
access to all cities in a country OR
access to all cities in a state / region OR
access to select cities in any state
or country.
What would be the best way to define this in the database (if the db has a Country table, State / Region table, City table and a Client table)?
Clarification:
(A simplified view of the tables with only the essential columns pertaining to this question).
Country table -
idCountry | Name
State table -
idState | idCountry | Name
City table -
idCity | idState | Name
Client table -
idClient | Name
You could to create a Location self related table (Id, Name, ParentLocation) and a AccessControl table (ClientId, LocationId). When a client is related to a location, you could grant access to all location below it. Some examples:
ID Name Parent
-------------------
1 World NULL -- Need to represent all countries
2 Brazil 1 -- A country
3 São Paulo 2 -- A state
4 São Paulo 3 -- A city
If you want to stick your current model, maybe a table like (ClientId, CountryId nullable, StateId nullable, CityId nullable). This way you could define your security access as your definition, but would need to deal with nullable fields.