Multiple SQL Update Statements in single query - sql

I am in a situation where I am having to update about 12,000 items in my DB.
Each row needs to mirror an excel file that I made previously.
I have made the file that creates each line of SQL statement, but I am not sure if I can run each line in a single query.
This is an example of what I am trying to do.
UPDATE [STORESQL].[dbo].[RPT_ITM_D] SET F1301='1.29' WHERE F01='0000000000001'
UPDATE [STORESQL].[dbo].[RPT_ITM_D] SET F1301='1.39' WHERE F01='0000000000002'
Will this work, or are there any better options for what I am trying to achieve?
Each item will have a unique value and the column to be changed will have a unique value as well. I don't see how I could make this work with a loop, or any other methods I've found so far. I realize that this might take a long time to process, but time is not an issue.
Thank you in advance

Something like this is the best you can do:-
UPDATE [STORESQL].[dbo].[RPT_ITM_D]
SET F1301 =
case F01
when '0000000000001' then '1.29'
when '0000000000002' then '1.30'
ELSE F1301
end
Other than that, running multiple updates is the way to go.

Yes, you could add all the single-line-Update-statements in one query like you are doing.

Take a look at MERGE e.g. something like:
MERGE INTO [STORESQL].[dbo].[RPT_ITM_D]
USING (
VALUES ('1.29', '0000000000001'),
('1.39', '0000000000002')
) AS source (F1301, F01)
ON F01 = source.F01
WHEN MATCHED THEN
UPDATE
SET F1301 = source.F1301;
...but using a table value constructor in this way would not scale to 12,000 rows! So look to first copying the data from Excel to a table on the server, then use the table as the source e.g.
MERGE INTO [STORESQL].[dbo].[RPT_ITM_D]
USING [STORESQL].[dbo].MyStagingTable AS source
ON F01 = source.F01
WHEN MATCHED THEN
UPDATE
SET F1301 = source.F1301;

If you have a significant amount of data to update, it may be advantageous to load the excel file into the database as a table, then update your table based on the data in this loaded table.
UPDATE RPT_ITM_D
SET F1301 = NewTable.Value
FROM RPT_ITM_D INNER JOIN NewTable ON (NewTable.F01 = RPT_ITEM_D.F01);
If you're on SQL server, you could use SSIS to load the file pretty quickly.

I think the best way is to import the Excel sheet into a table in your SQL database. From there you could be able to use a join to create a single update statement for all 12,000 items.
For information on how to import Excel sheet into SQL: http://msdn.microsoft.com/en-us/library/ms141209.aspx
The update statement would then look something like this:
UPDATE itemTable
SET F1301 = excelTable.<column with your value>
FROM [STORESQL].[dbo].[RPT_ITM_D] itemTable inner join [STORESQL].[dbo].[importedExcelTableName] excelTable on itemTable.F01 = excelTable.<column with the item code>
If you aren't sure if this would work safely, you can try this query for a single value by simple adding:
WHERE itemTable.F01 = '0000000000001'

You can use the concatenate function in Excel to frame a query, All you need to do is to frame a single update query and drag the same for the rest
concatenate("Update set =",,",where =
",,";")
Use the above format and drag the cell till the end or double click on the bottom right corner for Auto fill of the Update statement. I beleive this is the shortest way possible and run it in a single Go.

Make a unique constraint on the F01 column and then use an insert statement with an 'ON DUPLICATE KEY UPDATE' statement.
INSERT INTO [STORESQL].[dbo].[RPT_ITM_D] (F01, F1301)
VALUES
('0000000000001','1.29'),
('0000000000002','1.39')
ON DUPLICATE KEY UPDATE F1301 = VALUES(F1301);

Related

SQL update multiple rows with different values where they match a value from a list

So perhaps the title is a little confusing. If you can suggest better wording for that please let me know and i'll update.
Here's the issue. I've got a table with many thousands of rows and i need to update a few thousand of those many to store latest email data.
For example:
OldEmail#1.com => NewEmail#1.com
OldEmail#2.com => NewEmail#2.com
I've got a list of old emails ('OldEmail#1.com','OldEmail#2.com') and a list of the new ('NewEmail#1.com','NewEmail#2.com'). The HOPE was was to sort of do it simply with something like
UPDATE Table
SET Email = ('NewEmail#1.com','NewEmail#2.com')
WHERE Email = ('OldEmail#1.com','OldEmail#2.com')
I hope that makes sense. Any questions just ask. Thanks!
You could use a case expression:
update mytable
set email = case email
when 'OldEmail#1.com' then 'NewEmail#1.com'
when 'OldEmail#2.com' then 'NewEmail#2.com'
end
where email in ('OldEmail#1.com','OldEmail#2.com')
Or better yet, if you have a large list of values, you might create a table to store them (like myref(old_email, new_email)) and join it in your update query, like so:
update t
set t.email = r.new_email
from mytable t
inner join myref r on r.old_email = t.email
The actual syntax for update/join does vary accross databases - the above SQL Server syntax.
With accuracy to the syntax in particular DBMS:
WITH cte AS (SELECT 'NewEmail#1.com' newvalue, 'OldEmail#1.com' oldvalue
UNION ALL
SELECT 'NewEmail#2.com', 'OldEmail#2.com')
UPDATE table
SET table.email = cte.newvalue
FROM cte
WHERE table.email = cte.oldvalue
or, if CTE is not available,
UPDATE table
SET table.email = cte.newvalue
FROM (SELECT 'NewEmail#1.com' newvalue, 'OldEmail#1.com' oldvalue
UNION ALL
SELECT 'NewEmail#2.com', 'OldEmail#2.com') cte
WHERE table.email = cte.oldvalue
Consider prepared statement for rows update in large batches.
Basically it works as following :
database complies a query pattern you provide the first time, keep the compiled result for current connection (depends on implementation).
then you updates all the rows, by sending shortened label of the prepared function with different parameters in SQL syntax, instead of sending entire UPDATE statement several times for several updates
the database parse the shortened label of the prepared function , which is linked to the pre-compiled result, then perform the updates.
next time when you perform row updates, the database may still use the pre-compiled result and quickly complete the operations (so the first step above can be skipped).
Here is PostgreSQL example of prepare statement, many of SQL databases (e.g. MariaDB,MySQL, Oracle) also support it.

Structuring many update statements in SQL Server

I'm using SQL Server. I'm also relatively new to writing SQL... in a strong way. It's mostly self-taught, so I'm probably missing key ideas in terms of proper format.
I've a table called 'SiteResources' and a table called 'ResourceKeys'. SiteResources has an integer that corresponds to the placement of a string ('siteid') and a 'resourceid' which is an integer id that corresponds to 'resourceid' in ResourceKeys. ResourceKeys also contains a string for each key it contains ('resourcemessage'). Basically, these two tables are responsible for representing how strings are stored and displayed on a web page.
The best way to consistently update these two tables, is what? Let's say I have 5000 rows in SiteResources and 1000 rows in ResourceKeys. I could have an excel sheet, or a small program, which generates 5000 singular update statements, like:
update SiteResources set resoruceid = 0
WHERE siteid IS NULL AND resourceid IN (select resourceid
from ResourceKeys where resourcemessage LIKE 'FooBar')
I could have thousands of those singular update statements, with FooBar representing each string in the database I might want to change at once, but isn't there a cleaner way to write such a massive number of update statements? From what I understand, I should be wrapping all of my statements in begin/end/go too, just in-case of failure - which leads me to believe there is a more systematic way of writing these update statements? Is my hunch correct? Or is the way I'm going about this correct / ideal? I could change the structure of my tables, I suppose, or the structure of how I store data - that might simplify things - but let's just say I can't do that, in this instance.
As far as I understand, you just need to update everything in table SiteResources with empty parameter 'placement of a string'. If so, here is the code:
UPDATE a
SET resourceid = 0
FROM SiteResources a
WHERE EXISTS (select * from ResourceKeys b where a.resourceid = b.resourceid)
AND a.siteid IS NULL
For some specific things like 'FooBar'-rows you can add it like this:
UPDATE a
SET resourceid = 0
FROM SiteResources a
WHERE EXISTS (select * from ResourceKeys b where a.resourceid = b.resourceid and b.resourcemessage IN ('FooBar', 'FooBar2', 'FooBar3', ...))
AND a.siteid IS NULL
Let me see if I understood the question correctly. You'd like to update resourceid to 0 if the resourcemessage corresponds to a list of strings ? If so, you can build your query like this.
UPDATE r
SET resourceid = 0
FROM SiteResources r
JOIN ResourceKeys k ON r.resourceid = k.resourceid
WHERE k.resourcemessage IN ('FooBar', ...)
AND r.siteid IS NULL;
This is using an extended UPDATE syntax in transact-sql allowing you to use a JOIN in the UPDATE statement. But maybe it's not exactly what you want ? Why do you use the LIKE operator in your query, without wildcard (%) ?
With table-valued parameters, you can pass a table from your client app to the SQL batch that your app submits for execution. You can use this to pass a list of all the strings you need to update to a single UPDATE that updates all rows at once.
That way you don't have to worry about all of your concerns: the number of updates, transactional atomicitty, error handling. As a bonus, performance will be improved.
I recommend that you do a bit of research what TVPs are and how they are used.

SQL Match and Replace

I have to update a table in my sql server with data from an excel sheet It is a lot of parts I need to update and I need to update two columns in a 12 column table. What would be the easiest way doing this?
I was thinking access? I tried to do a SSIS job on the specific two columns but it failed.
Please help and thanks.
One way of doing it is to import the Excel file into your sql database and then do the update with a simple update statement like his:
UPDATE YourTable
SET Column1 = ExcelImported.Column1,
Column2 = ExcelImported.Column2
FROM YourTable
JOIN ExcelImported
ON YourTable.Key = ExcelImported.Key

Update A multi-valued field in Access

I have created a lookup table in Access to provide the possible values for a column. Now I need to update this column with the data it had before I converted the column. I am unable to figure out a SQL Query that will work. I keep getting the error "An UPDATE or DELETE query cannot contain a multi-valued field." My research has suggested that I just need to set the value of the column but this always updates 0 records:
UPDATE [table_name] SET [column_name].Value = 55 WHERE [table_name].ID = 16;
I know this query will work if I change it to update a text column, so it is definitely a problem with just this column.
If you're adding a value to your multi-valued field, use an append query.
INSERT INTO table_name( [column_name].Value )
VALUES (55)
WHERE ID = 16;
If you want to change one particular value which exists in your multi-valued field, use an UPDATE statement. For example, to change the 55 to 56 ...
UPDATE [table_name]
SET [column_name].Value = 56
WHERE [column_name].Value = 55 And ID = 16;
See Using multivalued fields in queries for more information.
I have figured this out! It certainly was counter-intuitive! You have to use an INSERT statement to do the update.
-- Update a record with a multi-valued field that has no value
INSERT INTO [table_name] ( [[column_name].[Value] )
VALUES(55)
WHERE [table_name].ID = 16;
This confused me because I was expecting an UPDATE statement. I think it actually inserts a record into a hidden table that is used to associate multiple values with this column.
I am working with Sharepoint, I created the tables as multi-value fields, ran into the error with my INSERT INTO statement, went back to Sharepoint to change to non-multi-value fields, but that didn't fix it.
Recreated the table without using multi-value fields, and the INSERT INTO worked just fine.
do not use the .value part
UPDATE [table_name] SET [column_name] = 55 WHERE [table_name].ID = 16;
INSERT INTO Quals (cTypes.[value])
SELECT Quals_ContractTypes.ContractType
FROM Quals_ContractTypes
WHERE (Quals.ID = Quals_ContractTypes.ID_Quals);
I gotta say I didn't understand very well your problem but I saw something strange in your query. Try this:
UPDATE [table_name] SET [column_name]= 55 WHERE [table_name].ID = 16;
UPDATE:
Look at this link: it has an example
UPDATE Issues
SET Issues.AssignedTo.Value = 10
WHERE (((Issues.AssignedTo.Value)=6)
AND ((Issues.ID)=8));
NOTES
You should always include a WHERE
clause that identifies only the
records that you want to update.
Otherwise, you will update records
that you did not intend to change. An
Update query that does not contain a
WHERE clause changes every row in the
table. You can specify one value to
change.
The Multi-Valued field refers to Access databases that have tables with columns, that allow you to select multiple values, like a Combo Checkbox list.
THOSE are the only Access types that SQL cannot work with. I've tested all Access lookup possibilities, including hard-coded values, and lookup tables. They work fine, but if you have a column that has the Allow Multiple select options, you're out of luck. Even using the INSERT INTO as mentioned below, will not work as you'll get a similar but different error, about INSERTing into multi-valued fields.
As mentioned it's best to avoid using such tables outside of Access, and refer to a table specifically for your external needs. Then write a macro/vba script to update the real tables with the data from the "auxiliary" table.

SQL cell wise trigger

Can a specific cell wise trigger be created?
Or is
IF UPDATE(COLUMN) WHERE OTHER_COLUMN LIKE 'JT'
the equivalent present in SQL Server 2008?
EDIT after getting 2nd answer---
IF not UPDATE(CurrentNo) --// Wanted to do like this : where series ='JT'
return
IF not EXISTS(SELECT 'True'
FROM Inserted i
JOIN Deleted d ON i.Series = d.Series
WHERE i.Series = 'JT' AND d.Series = 'JT')
return
Seems ok right! Please comment.
No. There is no way of doing this declaratively. You would need to create a general Update trigger and put logic in it to return immediately IF NOT UPDATE (column)
If the column of interest was updated then you would query the inserted and deleted pseudo tables to allow you to process rows where your condition of interest was met.
Tiggers are specified on tables, not on rows, columns or cells. Inside the body of the trigger you will have access to the INSERTED and DELETED tables. You can join them together to deterimine which columns were changed during an update. The UPDATE() function which is available in SQL Server 2008 (as well as previous versions) is a shorthand method for determining whether a column has changed.