Entering Excel data into SQL using where - sql

I have this excel table(it's just for the example):
and i have in the SQL table just with the colors.
i want to insert new column with the numbers like:
insert into table colors
set number = 'c'
where color = 'RED'
but i have 1500 records to add and i can't do it like this..
how can i do it?
thanks

First, you need to a add column in your SQL table (let's call it sql_table). I am assuming the colors in your excel table are a subset of the colors in your sql_table.
alter table sql_table
add color_id varchar(100) --change datatype/length as desired
Then you could bulk upload that file into SSMS as a new table (during upload/import make sure to set datatypes to be the same as your sql_table (let's call this new table excel_table)
Finally, update your sql_table by joining on to your excel_table. I am assuming the sql_table has 1 row per color.
update sql_table a
join excel_table b on a.color = b.color
set a.color_id = b.color_id;
If you wish, you can drop that excel_table since your sql_table is updated

You shouldn't need to know the database to write an SQL insert OR update. SQL is universal. Only flavors like MySql and T-SQL include language components foreign to SQL.
https://www.mysqltutorial.org/mysql-insert-statement.aspx
Updates
Only saw your actual question after reading the comments. First, create an Excel column which concatenates the update script.
=concatenate("update colors set number = '", B1, "' where color = '", A1, "'")
Creates
First, create an Excel column which concatenates the values into the format:
('color', 'number'),
=concatenate("('", A1, "', '", B1, "'),")
Be aware with SQL Server, you can only insert 1000 rows at a time.
insert into colors values
(paste rows here)
(remove comma from last line)
You only need to specify the table structure in the query if your input data is not in the same form as the table, which you can control.

what i did was so easy,
i just copy the data from the excel to SSMS:
1. right click--> edit 200 top rows. and i past the data.
the i did what u write:
update sql_table a
join excel_table b
on a.color = b.color
thanks to you all

Related

Updating or inserting SQL Server destination table data based on conditions from source table data

I have two SQL Server tables, one is my destination table (LocaleStringResource), the other one is the source table (TempResourceSunil).
Source table has the following columns: TempResourceSunil
[ID], [LanguageId], [ResourceName], [ResourceValue], [Burmese], [Unicode]
and the destination table's columns are LocaleStringResource
[Id], [LanguageId], [ResourceName], [ResourceValue]
I want to update the destination table [ResourceValue] based on [ResourceName] from the source file.
Example:
[ResourceName] = 'Account.AccountActivation'
means I want to check it have corresponding Burmese [ResourceValue] in LocaleStringResource table if it does not exist, I will take it from TempResourceSunil and Burmese column and insert it into LocaleStringResource with language id =2.
Same if [ResourceValue] for Unicode (language id = 3) does not exist for [ResourceName] = 'Account.AccountActivation' means I want to insert [ResourceValue] from TempResourceSunil with language id = 3.
Can any SQL expert help me?
The description you gave isn't really fleshed out however, you want to use a Case Statement. CASE STATEMENT INFO
A case statement can have multiple WHENs to cover multiple logic statements. You can even have one inside the other. I wouldn't really do that for this situation.
The example below is just a simple version.
If l.[ResourceValue] is null and l.[ResourceName] = 'Account.AccountActivation' then use the value of T.[Burmese] for column l.[ResourceValue]. ELSE means if no When within the case statement is true, then use this value.
Also be aware that if you are trying to use an INT value from the first table in a string column on the 2nd, you need to cast it as a varchar.
Test out your logic and case statements and see how you get on.
SELECT
l.[Id],
l.[LanguageId],
l.[ResourceName],
CASE WHEN l.[ResourceName] = 'Account.AccountActivation' and l.[ResourceValue] is null then T.[Burmese]
else l.[ResourceValue] end as [ResourceValue],
T.[ID],
T.[LanguageId],
T.[ResourceName],
T.[ResourceValue],
T.[Burmese],
T.[Unicode]
FROM LocaleStringResource as L
LEFT JOIN TempResourceSunil t on (t.ID = L.ID) and (t.[LanguageId] = l.[LanguageId])

How to append to existing TEXT row [sqlite3]

I would like to take an existing TEXT field/row and append to it with sqlite3. I'm finding it somewhat difficult, I've seen some stuff with "upsert."
SQLite - UPSERT *not* INSERT or REPLACE
The specific database I'm working with has no relational connections to any other tables.
Assuming the ideal (pseudo code) UPDATE Table APPEND row values(" text")
assuming row contains "my " I would like it to result in "my text"
Ideally I would like to do this in a single query, but until then I'm left to selecting and using update set
You can use the current values of columns in an update:
UPDATE yourtable SET somecol = somecol || 'text' WHERE somecondition;

MySQL; Split one column into multiple columns;data changes daily

This is a common question, but I found my problem to be unique. I have a database in MySQL workbench that has multiple order number (inconsistent length) and status conditions (three types) in a single column. I must separate the order numbers from their status and the order numbers from each other.
What I have:
|NUMBER_STATUS|
|1234-START, 12323-END|
|234 - END, 12423-START, 53443-WIP|
What my final output should be:
|Number_STATUS_1| |Number_STATUS_2| |Number_STATUS_3|
1234 12323
234 12423 53443
There are over 25,000 data points. So far, I have tried writing a left function:
SELECT *,
LEFT(NUMBER_STATUS, locate('-START', NUMBER_STATUS)-1) AS 'NUMBER_STATUS_1'
FROM Request;
This function does exactly what I want: Creates a new column with the status removed, but does not carry over any other data in its row.
I thought of three plans to attack this:
create new columns split the original by pieces. I can do this in excel using "split text into cells" and then bring it into MySQL Workbench, but I know SQL is more powerful, so I would like to write a script for this.
Create a pseudo table that stores each new column (Number status 1, number status 2, etc) but the data changes daily so I don't want to limit the number of new columns that can be created.
Ask you all.
Some other links I referenced for help:
Split one column to multiple columns but data will vary SQL
Split string and return data in multiple columns
But my knowledge of SQL is still growing and I have no idea what these functions mean, I would greatly appreciate the help.
This is what I used to solve my problem:
I altered table and column names for personal reasons. I hope this helps other people in the future!
/*remove status name from data*/
Update table
Set
columnSTATUS = REPLACE(columnSTATUS, '-status1', '');
Update table
Set
columnSTATUS = REPLACE(columnSTATUS, '-staus2', '');
Update table
Set
columnSTATUS = REPLACE(columnSTATUS, '-status3', '');
/*split data into columns*/
UPDATE table SET
`column1` = IF (
LOCATE(',', columnSTATUS) >0,
SUBSTRING(columnSTATUS, 1,LOCATE(',', columnSTATUS)-1),
column_STATUS
),
`column2` = IF(
LOCATE(',', columnSTATUS) > 0,
SUBSTRING(columnSTATUS, LOCATE(',', columnSTATUS)+1),
'');
UPDATE table SET
`column3` = IF (
LOCATE(',', column2) >0,
SUBSTRING(column2, LOCATE(',', column2)+1), '');
UPDATE table SET
`column4` = IF (
LOCATE(',', column3) >0,
SUBSTRING(column3, LOCATE(',', column3)+1), '');
/*remove data remaining in column after commas*/
UPDATE table SET
column2 = SUBSTRING_INDEX(column2, ',', 1);
UPDATE Service_Request SET
column3 = SUBSTRING_INDEX(column3,',',1);
NB: I do not have a choice how the data is imported.

How to Update a Single record despite multiple Occurances of the same ID Number?

I have a table that looks like the below table:
Every time the user loan a book a new record is inserted.
The data in this table is derived or taken from another table which has no dates.
I need to update this tables based on the records in the other table: Meaning I only need to update this table based on what changes.
Example: Lets say the user return the book Starship Troopers and the book return is indicated to Yes.
How do I update just that column?
What I have tried:
I tried using the MERGE Statement but it works only with unique rows of data, meaning you get an error if the same ID appears more than once.
I also tried using a basic UPDATE Statement and a JOIN but that's not going well.
I am asking because I have ran out of ideas.
Thanks for reading
If you need to update BooksReturn in target table based on the same column in source table
UPDATE t
SET t.booksreturn = s.booksreturn
FROM target t JOIN source s
ON t.userid = s.userid
AND t.booksloaned = s.booksloaned
Here is SQLFiddle demo
You can do this by simple Update & Insert statement.....
Two table A & B
From B you want to insert data into A if not exists other wise Update that data....
,First Insert into temp table....
SELECT *
INTO #MYTEMP
FROM B
WHERE BOOKSLOANED NOT IN (SELECT BOOKSLOANED
FROM A)
,Second Check data and insert into A.
INSERT INTO A
SELECT *
FROM #MYTEMP
And at last write one simple update statement which update all data of A. If any change then it also reflect to that data otherwise data as it is.
You can also update from #MYTEMP table.

Look Up Table in SQL

I basically have a table A with 30 million records and I want to add a column entitled "TYPE" to the table. I have a look up table B that maps a code to a color. I want to iterate through table A and compare the code in TABLE A to the code in TABLE B and then add the color to the TYPE column in table A. Is this possible? What would be the best approach to this problem? The codes in table B don't match perfectly with the actual codes in table A.
hard to say without seeing the schema or knowing the DBMS but, if it's always a the first 2 digits of the code used to look up the color, why not
UPDATE table_a SET type = SUBSTR(code, 2)
and do a JOIN normally
you could do a join like
JOIN table_b ON table_b.id = SUBSTR(table_a.code,2)
but that would hardly be performant.
Give or take issues with size of transaction, isn't it a simple ALTER TABLE to add the column and an UPDATE to fix it?
ALTER TABLE TableA ADD (Type VARCHAR(10));
UPDATE TableA
SET Type = ((SELECT Colour FROM TableB WHERE TableA.Type = TableB.Type));
The only tricky bit might be the double parentheses; they're needed in some DBMS and may not be needed in others (single parentheses may be sufficient). You may also be able to use a UPDATE with a JOIN; the syntax isn't entirely standard there, either.
Note that this mapping relies on a change of NULL to NULL being a no-op. If you have values in some rows but not all of those rows match an entry in TableB, then you need to be careful with an full-table UPDATE like that. It will set the Type for any rows in TableA for which there is no match in TableB to NULL. If that wasn't what you needed, you'd either use an UPDATE with JOIN or you'd write:
UPDATE TableA
SET Type = ((SELECT Colour FROM TableB WHERE TableA.Type = TableB.Type));
WHERE Type IN (SELECT Colour FROM TableB WHERE TableA.Type = TableB.Type);
In the current case, where the column is newly added and therefore contains NULL anyway, there is no harm done omitting the WHERE clause on the UPDATE itself.
You can do the update just by looking at the first characters of the code in table B, as in the following statement:
update table_a
set table_a.type = table_b.type
from table_b
where table_b.code = substr(table_a.code, 1, length(table_b.code))
This may be a bit slow, since you cannot use any indexes to speed it up. However, if table_b is small, then the performance may be acceptable.