Will this UPDATE accomplish what I intend it to? - sql-server

This is probably a very simple question for you SQL folks out there.
I have a temp table (TMP_VALIDATION_DATA) in which I've stored the old and new values of some fields I wish to update in a production table (PROVIDER_SERVICE), plus the uuids of the PROVIDER_SERVICE records that need to be updated.
What I want to accomplish is this, in pseudo-code:
For every prov_svc_uuid uuid in TMP_VALIDATION_DATA table
Set PROVIDER_SERVICE_RATE.END_DATE = NewPvSvcEndDate
Where [uuid in temp table] = [uuid in PROVIDER_SERVICE table]
end for
Is this Update statement going to accomplish what I need?
update PROVIDER_SERVICE
set END_DATE = (
select NewPvSvcEndDate
from TMP_VALIDATION_DATA T
where T.PROVIDER_SERVICE_UUID = PROVIDER_SERVICE.PROVIDER_SERVICE_UUID
)
If my UPDATE is incorrect, will you please provide the correction? Thanks.

Your query will update all records and you might get an error if you have more than one record in your subquery. I would also change your syntax to a JOIN similar to below.
update P
set END_DATE = T.NewPvSvcEndDate
FROM PROVIDER_SERVICE P
JOIN TMP_VALIDATION_DATA T
ON P.PROVIDER_SERVICE_UUID = T.PROVIDER_SERVICE_UUID
If you don't want to UPDATE all records, then add a WHERE clause.
My suggestion is if you don't know how many records would be included in the UPDATE, write your query as a SELECT first, then change it to an UPDATE. So for this one:
SELECT P.END_DATE, T.NewPvSvcEndDate
FROM PROVIDER_SERVICE P
JOIN TMP_VALIDATION_DATA T
ON P.PROVIDER_SERVICE_UUID = T.PROVIDER_SERVICE_UUID

This will either update all records, or error out (not sure what happens when you try to update a column with multiple values like that).

Related

SQL Server Trigger to alter different table

I’m trying to create a trigger to change the value of a column in table B if it finds the information in a column in table A.
An example of my database is below:
[TableA],
itemID
[TableB],
itemID
itemInStock
Once a user creates an entry in Table A declaring an itemID, the trigger needs to change the TableB.itemInStock column to ‘Yes’
I’m still learning SQL so excuse me if I’ve missed something, let me know if you need any more info.
I understand there are better ways of doing this but I've been told I need to do this using a trigger.
I've attempted a few different things, but as it stands nothing is working, below is the current solution I have however this updates all itemInStock rows to 'Yes', where as I only want the ones to update where the TableB.itemID matches the itemID entered in TableA.
ALTER TRIGGER [itemAvailability] ON [dbo].[TableA] FOR
INSERT
AS
BEGIN
UPDATE [dbo].[TableB] set itemInStock = 'Yes' WHERE
TableB.itemID = itemID
END
Two problems -
you're not looking at the Inserted pseudo table which contains the
newly inserted rows
you're assuming the trigger is called once per row - this is not the
case, the trigger is called once per statement and the Inserted
pseudo table will contain multiple rows - and you need to deal with
that
So, your code should look like this -
ALTER TRIGGER [itemAvailability] ON [dbo].[TableA]
FOR INSERT
AS
UPDATE TB
SET itemInStock = 'Yes'
FROM [dbo].[TableB] TB JOIN inserted I
on TB.itemID = I.itemID

TSQL Update Table from Import Table

I'm currently working on a stored procedure in SQL Server 2012. I want to update a table from another table:
My query looks like this:
UPDATE [MySchema].[Delivery]
SET DeliveryId = (SELECT ID FROM #DeliveryIds)
WHERE PoolId = 1
Somehow this query doesn't work... Do you know how to solve this issue?
Thanks :)
I am going to assume that #DeliveryIds is TABLE variable defined and populated earlier in your stored procedure.
However, we don't know yet how to join that table against your [Delivery] table. You can do something like this:
UPDATE Delivery
SET DeliveryId = DIDS.ID
FROM #DeliveryIds DIDS
WHERE Delivery.PoolId = 1
and DIDS.????? = Delivery.?????
Replace the question marks with whatever columns these two tables join on.

Need to populate a column based on another column in another table

I'm probably overthinking this so here goes.
I have two tables. The first one I want to populate the CorporationId based off it's TokenId value.
dbo.UsersAccountLink:
And the table that I want to get the value from:
Company.Token:
Here is what I have but it's not set right so it will not run. I'm not sure how to do this:
INSERT INTO dbo.UsersAccountLink.CorporationId
Select CorporationId
From Company.Token
Where Company.Token.TokenId = dbo.UsersAccountLink.TokenId
I want to populate dbo.UsersAccountLink.CorporationId with the value in Company.Token.CorporationId based on the TokenId.
Help?!
Looks like you want to update versus insert...
update dbo.UsersAccountLink
set CorporationID =
(Select CorporationId
From Company.Token
Where Company.Token.TokenId = dbo.UsersAccountLink.TokenId)

Creating an Update Trigger

I have SQL Server 2008 database with two tables. The first table is called Shelf. The second table is called Product. Each Product will belong to a Shelf. Based on this, I have a table structure that looks like:
**Product**
ID (int)
ShelfID (int)
Description (text)
**Shelf**
ID (int)
AisleNumber (int)
TotalProducts (int)
When a Product is inserted or removed, I need to update the "TotalProducts" value in the associated shelf. In an attempt to try this, I'm using a Trigger. However, I do not fully understand how triggers work. Can someone please show me how to accomplish this?
Thank you
When you insert or update a product, you need to work out what ShelfIDs are affects. This is the INSERTED reference below. Then you need to work out the number of products for these ShelfIDs (the JOIN/COUNT bit) and update the Shelf table.
You'll also need something for DELETE too: just reference the special DELETED table
This will run as part of the INSERT/DELETE statement
CREATE TRIGGER TRG_Product_I On product FOR INSERT
AS
SET NOCOUNT ON
UPDATE
S
SET
TotalProducts = foo.NewTotalProducts
FROM
Shelf S
JOIN
(SELECT
ShelfID, COUNT(*) AS NewTotalProducts
FROM
INSERTED I
JOIN
product P ON I.ShelfID = P.ShelfID
GROUP BY
ShelfID
) foo ON S.ShelfID = foo.ShelfID

T-SQL: what COLUMNS have changed after an update?

OK. I'm doing an update on a single row in a table.
All fields will be overwritten with new data except for the primary key.
However, not all values will change b/c of the update.
For example, if my table is as follows:
TABLE (id int ident, foo varchar(50), bar varchar(50))
The initial value is:
id foo bar
-----------------
1 hi there
I then execute UPDATE tbl SET foo = 'hi', bar = 'something else' WHERE id = 1
What I want to know is what column has had its value changed and what was its original value and what is its new value.
In the above example, I would want to see that the column "bar" was changed from "there" to "something else".
Possible without doing a column by column comparison? Is there some elegant SQL statement like EXCEPT that will be more fine-grained than just the row?
Thanks.
There is no special statement you can run that will tell you exactly which columns changed, but nevertheless the query is not difficult to write:
DECLARE #Updates TABLE
(
OldFoo varchar(50),
NewFoo varchar(50),
OldBar varchar(50),
NewBar varchar(50)
)
UPDATE FooBars
SET <some_columns> = <some_values>
OUTPUT deleted.foo, inserted.foo, deleted.bar, inserted.bar INTO #Updates
WHERE <some_conditions>
SELECT *
FROM #Updates
WHERE OldFoo != NewFoo
OR OldBar != NewBar
If you're trying to actually do something as a result of these changes, then best to write a trigger:
CREATE TRIGGER tr_FooBars_Update
ON FooBars
FOR UPDATE AS
BEGIN
IF UPDATE(foo) OR UPDATE(bar)
INSERT FooBarChanges (OldFoo, NewFoo, OldBar, NewBar)
SELECT d.foo, i.foo, d.bar, i.bar
FROM inserted i
INNER JOIN deleted d
ON i.id = d.id
WHERE d.foo <> i.foo
OR d.bar <> i.bar
END
(Of course you'd probably want to do more than this in a trigger, but there's an example of a very simplistic action)
You can use COLUMNS_UPDATED instead of UPDATE but I find it to be pain, and it still won't tell you which columns actually changed, just which columns were included in the UPDATE statement. So for example you can write UPDATE MyTable SET Col1 = Col1 and it will still tell you that Col1 was updated even though not one single value actually changed. When writing a trigger you need to actually test the individual before-and-after values in order to ensure you're getting real changes (if that's what you want).
P.S. You can also UNPIVOT as Rob says, but you'll still need to explicitly specify the columns in the UNPIVOT clause, it's not magic.
Try unpivotting both inserted and deleted, and then you could join, looking for where the value has changed.
You could detect this in a Trigger, or utilise CDC in SQL Server 2008.
If you create a trigger FOR AFTER UPDATE then the inserted table will contain the rows with the new values, and the deleted table will contain the corresponding rows with the old values.
Alternative option to track data changes is to write data to another (possible temporary) table and then analyse difference with using XML. Changed data is being write to audit table together with column names. Only one thing is you need to know table fields to prepare temporary table.
You can find this solution here:
part 1
part 2
If you are using SQL Server 2008, you should probably take a look at at the new Change Data Capture feature. This will do what you want.
OUTPUT deleted.bar AS [OLD VALUE], inserted.bar AS [NEW VALUE]
#Calvin I was just basing on the UPDATE example. I am not saying this is the full solution. I was giving a hint that you could do this somewhere in your code ;-)
Since I already got a -1 from the above answer, let me pitch this in:
If you don't really know which Column was updated, I'd say create a trigger and use COLUMNS_UPDATED() function in the body of that trigger (See this)
I have created in my blog a Bitmask Reference for use with this COLUMNS_UPDATED(). It will make your life easier if you decide to follow this path (Trigger + Columns_Updated())
If you're not familiar with Trigger, here's my example of basic Trigger http://dbalink.wordpress.com/2008/06/20/how-to-sql-server-trigger-101/

Resources