I am trying to accomplish to update the column ListPrice adding 25 to its current value where the name is All-Purpose Bike Stands and update SellStartDate to tomorrow's date in the table Production.Product.
Using that updated price I want to insert a row into the table Production.ProductListHistory with the new ListPrice and also update the row in the Production.ProductHistory column named EndDate with tomorrow's date as well.
The tables definitions areas follows:
Production.Product:
ProductID int PK
Name varchar(50)
ProductNumber nvarchar(25)
ListPrice money
SellStartDate datetime
SellEndDate
Production.ProductListHistory:
ProductID int PK FK
StartDate datetime PK
EndDate datetime
ListPrice money
Here is what I have so far that continues to give me errors:
CREATE PROCEDURE UPDATE_AND_INSERT
(#newprice money)
AS
BEGIN
UPDATE AdventureWorks2008R2.Production.Product
SET #newprice = 25 + AdventureWorks2008R2.Production.Product.ListPrice
WHERE AdventureWorks2008R2.Production.Product.Name LIKE 'All-Purpose%'
#newprice = AdventureProduct.Production.Listprice
END
If I understood your question, Your UPDATE should be something like this
You can also create a table variable to store your deleted list price and then insert it into your history table
DECLARE #MyTableVar table(
ProductID int NOT NULL,
StartDate datetime,
EndDate datetime,
ListPrice money);
UPDATE AdventureWorks2008R2.Production.Product
Set ListPrice = 25 + AdventureWorks2008R2.Production.Product.ListPrice
OUTPUT inserted.ProductID,
inserted.SellStartDate,
inserted.SellEndDate,
deleted.ListPrice
INTO #MyTableVar
where AdventureWorks2008R2.Production.Product.Name Like 'All-Purpose%'
AND Listprice = AdventureProduct.Production.Listprice
Related
I want to provide an EndDate when the MainAccountNum already exist. The endDate should be applied to the MainAccountNumb with the earliest startDate.
So If I have a create table statement like this:
Create Table ods.CustomerId(
ScreenDate INT NOT NULL,
CustomerNum nvarchar(40) NOT NULL,
MainAccountNum nvarchar(40) not null,
ServiceNum nvarchar(40) not null,
StartDate datetime not null,
EndDate datetime not null,
UpdatedBy nvarchar(50) not null);
and say I encounter something in the CustomerNum, MainAccountNum, StartDate, and EndDate like below:
1467823,47382906,2019-08-26 00:00:00.000, Null
1467833,47382906,2019-09-06 00:00:00.000, null
When the second record is inserted with that same MainAccountNum the first record should get the startDate of the New Record. The startDate has a default constraint as GetDat() so in the end it should look like:
1467823,47382906,2019-08-26 00:00:00.000,2019-09-06 00:00:00.000
1467833,47382906,2019-09-06 00:00:00.000, null
Please Provide code examples of how this can be accomplished
In the stored procedure used to insert new record, have something like
begin tran
declare #startDate datetime
select top 1 #oldStartDate = StartDate
from ods.CustomerId
where MainAccountNum = #mainAccountNum
order by StartDate asc
if ##rowcount > 0
update ods.CustomerId set EndDate = #startDate
where MainAccountNum = #mainAccountNum and StartDate = #oldStartDate
insert ... <your new record here>
commit
I am assuming that (MainAccountNum, StartDate) tuple is unique and can be used as a key. If not, you have to use whatever is unique for your update statement.
I want to provide an EndDate when the MainAccountNum already exist. The endDate should be applied to the MainAccountNumb with the earliest startDate.
So If I have a create table statement like this:
Create Table ods.CustomerId(
ScreenDate INT NOT NULL,
CustomerNum nvarchar(40) NOT NULL,
MainAccountNum nvarchar(40) not null,
ServiceNum nvarchar(40) not null,
StartDate datetime not null,
EndDate datetime not null,
UpdatedBy nvarchar(50) not null);
and say I encounter something in the CustomerNum, MainAccountNum, StartDate, and EndDate like below:
1467823,47382906,2019-08-26 00:00:00.000, Null
1467833,47382906,2019-09-06 00:00:00.000, null
When the second record is inserted with that same MainAccountNum the first record should get the startDate of the New Record. The startDate has a default constraint as GetDat() so in the end it should look like:
1467823,47382906,2019-08-26 00:00:00.000,2019-09-06 00:00:00.000
1467833,47382906,2019-09-06 00:00:00.000, null
Please Provide code examples of how this can be accomplished
I would like to apply an update to the current records in my table that do not have an endDate but have this same situation. How would I apply that update to where I give the previous record an endDate please provide me with code to solve this issue. Thanks so much
Your CustomerId table has EndDate as not null, how did they end up being null. Anyway try this:
update CustomerId
set EndDate = (select min(t2.StartDate) from CustomerId t2
where t2.MainAccountNum = t1.MainAccountNum and t2.StartDate > t1.StartDate)
from CustomerId t1
where t1.EndDate is null
For clarification, are you looking for a trigger function that will update all rows with null EndDate fields and the same MainAccountNum as a newly inserted row?
if so, the following should work:
CREATE TRIGGER cust_trg
ON CustomerId
AFTER INSERT
AS
BEGIN
UPDATE CustomerId
SET EndDate = inserted.StartDate
WHERE EndDate IS NULL AND MainAccountNum = inserted.MainAccountNum AND StartDate = (SELECT MIN(StartDate) FROM CustomerId WHERE MainAccountNum = inserted.MainAccountNum AND EndDate IS NULL)
END;
Note that with the schema as written there should be no null values in EndDate column, so unless the schema is changed this trigger will never fire.
I have a program that captures orders into two SQL tables. One is a header table with order info that has OrderID as auto increment PK. The other is a details table which captures vendor, part_number, and quantity data.
I have an after insert trigger on the header table which is suppose to update a table in another database with order info and a total quantity of parts in that order.
Everything works fine except when the trigger goes to calculate the total number of parts in the details table. What is happening is the trigger fires before the data is written to the details table and always returns NULLs for the total quantity of parts. What's the best workaround for this? Am I using a wrong trigger?
OrderHeader Table
ID int
TransCode int
CustID int
StoreID int
Date datetime
OrderDetail
OrderID int
MFG nchar(3)
PartNumber nchar(35)
Qty int
ALTER TRIGGER [dbo].[trig_Update_PRIME]
on [Cleansweep].[dbo].[OrderHeader]
after insert
AS
BEGIN
declare #ID as int
declare #DateInput as date
declare #CustID as int
declare #transcode as int
declare #storeID as int
declare #TotItems as int
select #ID = (select ID from inserted)
select #DateInput = (select date from inserted)
select #CustID = (select CustID from inserted)
select #transcode = (select TransCode from inserted)
select #storeID = (select StoreID from inserted)
set #TotItems = ( select SUM(qty) FROM [Cleansweep].[dbo].[OrderDetail] where OrderID = #ID )
if #transcode = 0
begin
insert into PRIME.dbo.PRIME_RepCalls (Customer, Cores)
values (#CustID, #TotItems)
end
if #transcode = 1
begin
insert into PRIME.dbo.PRIME_RepCalls (Customer, NewReturns)
values (#CustID, #TotItems))
end
END
I belive that there two insert process in your DB - first one is when insert into Header table, and the second when is insert to Details table.
If you do insert Header first - than your trigger works before details of your documents were inserted in Db. That's why SUM can return NULL
I want to make a date constraint in my table (I use sql server). I want to make sure that the date in one of my columns is later than the current date and time (I know it sounds weird, but it's an assignment so I have no choice). I tried to do it this way:
ALTER TABLE sales ADD CONSTRAINT d CHECK (Date > CURRENT_TIMESTAMP);
but later when inserting DEFAULT into date column I get the following error:
The INSERT statement conflicted with the CHECK constraint "d".
The conflict occurred in database "Newsagents", table "dbo.Sales", column 'Date'.
This is the said table:
CREATE TABLE Sales (
ID INT IDENTITY(1,1) NOT NULL ,
ClientID INT REFERENCES Client(ClientID),
ProductNumber CHAR(10) REFERENCES Product(ProductNumber),
Quantity INT NOT NULL,
Price FLOAT NOT NULL ,
Date TIMESTAMP NOT NULL,
PRIMARY KEY ( ID )
and this how I insert my data into Sales column and get the constraint conflict:
DECLARE #counter INT
DECLARE #quantity int
DECLARE #prodNum varchar(20)
SET #counter = 0
WHILE #counter < 10
BEGIN
SET #quantity = (select FLOOR(RAND()*100))
SET #prodNum = (select TOP 1 ProductNumber from Product Order by NEWID())
insert into Sales (ClientID, ProductNumber, Quantity, Price, Date )
values(
(select TOP 1 ClientID from Client Order by NEWID()),
(select #prodNum),
(select #quantity),
((select #quantity)*(select TOP 1 Price from Product where ProductNumber = #prodNum)),
DEFAULT
)
SET #counter = #counter + 1
END
Is there a different way to do this? Or am I doing something wrong?
ALTER TABLE sales ADD CONSTRAINT d CHECK (Date > GETDATE());
change the Date column to datetime
I have problem with setting the formula in particular field. I am using sql database have been added from->add new item->sql database. I have orders table with following field:
ordernum primary key
orderdate smalldatetime,
custemail varchar(50),
subtotal money,
salestax money,
shipping money,
total AS(subtotal+salestax+shipping)
How to set this total formula, there is no datatype mentioned in total field.
Thanks,
Habib
This example should illustrate what you are looking to achieve.
create table #table
(
ordernum int identity(1,1) primary key,
orderdate smalldatetime,
custemail varchar(50),
subtotal money,
salestax money,
shipping money,
total AS(subtotal+salestax+shipping)
)
insert into #table
(
orderdate,
custemail,
subtotal,
salestax,
shipping
)
select
getDate(),
'some#email.com',
1.00,
1.00,
1.00
select * from #table
drop table #table
cheers, John