Correct this sql statement for Insert into, select, delete - sql

INSERT INTO Checkout(ProductID, MemberID, Quantity)
SELECT ProductID, MemberID, Quantity
FROM Cart
WHERE (MemberID = MemberID)
DELETE FROM CART WHERE (MemberID = MemberID)
The sql statement is workable until the Select, WHERE part but once I add the delete statement then the error (syntax error missing operator in query expression) comes out. The second MemberID is a value I gave for first MemberID parameter. Please help me to solve this as after I transfer the data from first table to second table then I need to delete the data from first table.
[Edit] Thanks to you all suggestions and now I realized that for WHERE (MemberID = MemberID)
will import entire table to new table and this statement also will delete the entire table contents. What can I do to make sure that the sql statement only delete the particulars members item?
Main Page>Member login page>Buy something>Item stored in shopping cart database (with member id)>display only particular member's bought item in shopping cart> proceed to checkout(only display that member item, delete shopping cart item)

The problem is with the second "MemberID". This needs to be a constant or have a variable name that doesn't conflict with the field name. A number of techniques for disambiguation are shown in a related SO post: How do you avoid column name conflicts?

You didn't mention what version of SQL Server you're using - but you might be able to use the OUTPUT clause for the DELETE statement to achieve what you're looking for. The OUTPUT clause was introduced in SQL Server 2005, so if you're on 2005 or newer, this code snippet should work for you:
Try this:
DELETE FROM dbo.CART
OUTPUT deleted.ProductID, deleted.MemberID, deleted.Quantity
INTO dbo.Checkout(ProductID, MemberID, Quantity)
WHERE MemberID = #MemberID
Basically this runs the DELETE statement against your dbo.Cart table, and it captures what rows have been deleted; those are then in turn inserted into the dbo.Checkout table.
Also - that condition in the WHERE clause seems quite funny - basically, this will select and thus delete all rows from your table......
Update: I'm assuming you somehow store the relevant member's ID in #MemberID and use that to select the rows to delete from the dbo.Cart table..

Store your passing data to a newly declared variable and use that variable to everywhere as below, this will work fine, thanks
DECLARE #PassedMemberID INT
SET #PassedMemberID = MemberID --Store your passing MemberID here for later use
INSERT INTO Checkout(ProductID, MemberID, Quantity)
SELECT ProductID, MemberID, Quantity
FROM Cart
WHERE (MemberID = #PassedMemberID)
DELETE FROM CART WHERE (MemberID = #PassedMemberID)

Related

Attempting to pull access form information into table with SQL

Currently, I am attempting to make a query that pulls the user's entry from an MS Access form and puts that entry into a table for later usage. This is what I have come up with so far, but I can't get it to save so hopefully this is either correctable or there is a different approach to this problem.
INSERT INTO tempOrder ('ProductID')
VALUES(
SELECT ProductID
FROM Product
WHERE ProductName is FORMS!Sandwich!sandwichChoice1
);
for insert select you should use
INSERT INTO tempOrder (ProductID)
SELECT ProductID
FROM Product
WHERE ProductName = FORMS!Sandwich!sandwichChoice1
and use = for compare

Sql Trigger After Insert Update another table with conditions

I am creating After Insert trigger , its working fine, but I have certain conditions before executing the statements inside the trigger
Based on Different CustomerId Run the trigger, I want check which CustomerId got inserted in my LoyaltyDetailsTable, say if last insert
was Customerid=2 then pass that Customerid in where condition then run
the trigger , or if Customerid = 1 then run the trigger for that Id,
so on.
I want to check whether in PriceClaimTable the inserted CustomerId exist or not, If exists then update the details else just insert the
values in LoyaltyDetailsTable only.
Trigger query
CREATE TRIGGER DetailsAfterInsert ON [dbo].[LoyaltyDetailsTable]
FOR INSERT
as
UPDATE PriceClaimTable
SET CurrentPoints =
(
(SELECT SUM(LoayaltyPointsTable.Points) AS RecentPoints FROM LoayaltyPointsTable
join LoyaltyDetailsTable ON LoayaltyPointsTable.LoyaltyPointsId
= LoyaltyDetailsTable.LoyaltyPointsId
WHERE CustomerId=1 and LoyaltyDetailsId= (SELECT MAX(LoyaltyDetailsId)
AS LoyaltyDetailsTable FROM LoyaltyDetailsTable))
+
(SELECT CurrentPoints FROM PriceClaimTable WHERE ClaimCustomerId=1 and
PriceClaimId=(SELECT max(PriceClaimId) FROM PriceClaimTable
))
)
WHERE ClaimCustomerId=1 and PriceClaimId=(SELECT max(PriceClaimId) FROM PriceClaimTable)
This is my first attempt to write a trigger, and here is table structure.
Any help would be great.
What you're looking for here is the inserted table. Every time you issue an UPDATE statement, SQL Server generates two virtual tables called inserted and deleted that store information on the data modifications you're making. These tables are accessible from your trigger. For more information, see here: https://msdn.microsoft.com/en-us/library/ms191300.aspx
You can use inserted to get the IDs you're looking for. So, instead of:
WHERE ClaimCustomerId=1
you can use:
WHERE ClaimCustomerId=inserted.ClaimCustomerId

Update SQL Server table with one time use values from another table

I have a table of users that has the usual suspects, name, email, etc. As the users complete an activity (queried from another table), I need to award them a gift card code.
update users
set giftcardcode = 'code from other table'
where email in (select email from useractivity where necessary conditions are met)
I have a table of unique gift card codes that are unique, one-time use codes. So I need to update my user table, setting the award code field equal to a distinct, unused gift card code from the gift card code table. Then I need to mark the 'used' field in the gift card table to 'Y'.
The goal is to do this with SQL and not any programming. I'm stumped.
I think there is a Many To Many relationship between User table and Activity table.
So, you can use a trigger to execute a query when update.
Each time a row will be updated in the Activity table, the trigger will do something.
It will UPDATE the User table by adding a new gift code.
I think you can add an attribute in your GiftCode table to easily check if the code as already been used. An you can get an unused code like that :
// Retrieve an unused code based on a BIT attribute.
SELECT TOP 1 [Code] FROM [GiftCode] WHERE IS_UNUSED = 1;
Don't forget to update this Gift code after using it.
You can use a SELECT statement including a sub SELECT statement to get a code too :
// Retrieve an unused code based on User table used codes.
SELECT TOP 1 [Code] FROM [GiftCode] WHERE [Code] NOT IN (SELECT [Code] FROM [User]);
It works well if you don't have too much users.
Otherwise , the first statement will be more efficient.
Don't forget to update the User table.
Now you can easily use one of these previous statement in a UPDATE statement.
It will be something like that :
UPDATE [User] SET [Code] = (
SELECT TOP 1 [Code] FROM [GiftCode] WHERE [Code] NOT IN (
SELECT [Code] FROM [User]))
WHERE USER_ID = // ...;
You can perform this in a trigger.
You can use a stored procedure, it's more efficient and will wrap all the SQL code in a compiled function. Then you can call it in your trigger.
You can execute a stored procedure in a job (see SQL Server Agent jobs) too.
create a Trigger on your table for update and do what you want inside it using inserted and deleted

SQL: I need to take two fields I get as a result of a SELECT COUNT statement and populate a temp table with them

So I have a table which has a bunch of information and a bunch of records. But there will be one field in particular I care about, in this case #BegAttField# where only a subset of records have it populated. Many of them have the same value as one another as well.
What I need to do is get a count (minus 1) of all duplicates, then populate the first record in the bunch with that count value in a new field. I have another field I call BegProd that will match #BegAttField# for each "first" record.
I'm just stuck as to how to make this happen. I may have been on the right path, but who knows. The SELECT statement gets me two fields and as many records as their are unique #BegAttField#'s. But once I have them, I haven't been able to work with them.
Here's my whole set of code, trying to use a temporary table and SELECT INTO to try and populate it. (Note: the fields with # around the names are variables for this 3rd party app)
CREATE TABLE #temp (AttCount int, BegProd varchar(255))
SELECT COUNT(d.[#BegAttField#])-1 AS AttCount, d.[#BegAttField#] AS BegProd
INTO [#temp] FROM [Document] d
WHERE d.[#BegAttField#] IS NOT NULL GROUP BY [#BegAttField#]
UPDATE [Document] d SET d.[#NumAttach#] =
SELECT t.[AttCount] FROM [#temp] t INNER JOIN [Document] d1
WHERE t.[BegProd] = d1.[#BegAttField#]
DROP TABLE #temp
Unfortunately I'm running this script through a 3rd party database application that uses SQL as its back-end. So the errors I get are simply: "There is already an object named '#temp' in the database. Incorrect syntax near the keyword 'WHERE'. "
Comment out the CREATE TABLE statement. The SELECT INTO creates that #temp table.

Need help to transfer data from one table to another table in the same database

I'm using visual studio 2008 express running C#. I got Cart table and Checkout table in the same database which is an access file. both table have 3 same column which is ProductID,MemberID and Quantity.
So when I click a button in the Shopping cart page, the data in Cart table are supposed to transfer to Checkout table and the data in Cart are supposed to be cleared (which I haven't try yet because the transfer part is not successful). In the configure data source, SQL statement Insert part I wrote:
INSERT INTO [Checkout]
([ProductID], [MemberID], [Quantity])
VALUES (?, ?, ?)
SELECT([ProductID], [MemberID], [Quantity])
FROM [Cart]
WHERE ([MemberID]=?)
and the error is (Missing semicolon (;) at end of SQL statement.) come out at the aspx.cs (adsCart.Insert(); ) when I run it. When I try to execute query in configure datasource , the error is (Unable to parse query text.)
(I have also tried another way where the code is
string MemberID = User.Identity.Name;
string Product = ??? ;
string Quantity =??? ; (Both ??? is the part where I do not know what to put in.)
adsCart1.SelectParameters["MemberID"].DefaultValue = MemberID;
adsCart1.SelectParameters["ProductID"].DefaultValue = ProductID;
adsCart1.SelectParameters["Quantity"].DefaultValue = Quantity;
adsCheckout.InsertParameters["ProductID"].DefaultValue = ProductID;
adsCheckout.InsertParameters["MemberID"].DefaultValue = MemberID;
adsCheckout.InsertParameters["Quantity"].DefaultValue = Quantity;
adsCheckout.Insert();
But I do not know what to put in for the 2 ??? part so I only managed to transfer the memberID to the Checkout Table.)
Sorry if the Question is too long. Please help me to solve this problem or tell me the better way to transfer data from one table to another table. I also need help in creating simple search engine for products for my website.
INSERT INTO [Checkout] ([ProductID], [MemberID], [Quantity])
SELECT [ProductID], [MemberID], [Quantity]
FROM [Cart]
WHERE [MemberID]=?
Use SQL are per your first thoughts. The above statement should get the values you require. All you need to do is specify a member ID in the Where clause.
More information :
http://msdn.microsoft.com/en-us/library/ms188263.aspx
http://msdn.microsoft.com/en-us/library/ms189872.aspx