I'm trying to get the latest date from my OrderItem table using sql, asp.net. However, when i run the program, they show this error: Incorrect syntax near the keyword 'from'.
Here are my codes:
string strconnect = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strconnect);
string command = "
Select OrderItem.ProductID, Product.Name, OrderItem.TotalQty, Product.UnitPrice, OrderItem.TotalPrice
FROM OrderItem
INNER JOIN Product ON OrderItem.ProductID=Product.ProductID
WHERE OrderDate = MAX(OrderDate) from OrderItem";
SqlCommand cmd = new SqlCommand(command, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
myConnect.Close();
Please advise!
You need to remove "from OrderItem" in your WHERE condition since you have specified in your FROM clause.
SELECT
i.ProductID,
p.Name,
i.TotalQty,
p.UnitPrice,
i.TotalPrice
FROM
OrderItem i
INNER JOIN Product p
ON i.ProductID = p.ProductID
WHERE
i.OrderDate = (SELECT MAX(OrderDate)
FROM OrderItem
WHERE OrderItem.ProductID = i.ProductID)
SELECT o.ProductID, p.Name, o.TotalQty, p.UnitPrice, o.TotalPrice
FROM OrderItem AS o
INNER JOIN Product AS p ON o.ProductID = p.ProductID
ORDER BY o.OrderDate DESC
LIMIT 1
Ahh, you are using SQL-server, try this: (however not tested)
SELECT TOP 1 o.ProductID, p.Name, o.TotalQty, p.UnitPrice, o.TotalPrice
FROM OrderItem AS o
INNER JOIN Product AS p ON o.ProductID = p.ProductID
ORDER BY o.OrderDate DESC
It depends on what is data type of order date. You may need to change the data type of the variable or apply truncation.
declare @MaxOrderDate datetime
select @MaxOrderDate = MAX(OrderItem.OrderDate) from OrderItem
Select
OrderItem.ProductID,
Product.Name,
OrderItem.TotalQty,
Product.UnitPrice,
OrderItem.TotalPrice
FROM
OrderItem
INNER JOIN Product
ON OrderItem.ProductID=Product.ProductID
WHERE
OrderItem.OrderDate = @MaxOrderDate
You should change the subquery in the WHERE clause.
SELECT OrderItem.ProductID, Product.Name, OrderItem.TotalQty, Product.UnitPrice, OrderItem.TotalPrice
FROM OrderItem
INNER JOIN Product ON OrderItem.ProductID=Product.ProductID
WHERE OrderDate = ( SELECT MAX(OrderDate) FROM OrderItem );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.