我试图将值插入结算表格。对于BillingAmount,我希望根据客人退房的时间进行更改。如果客人在中午之前退房,那么我希望BillingAmount只是QuotedRate乘以他们住的晚数。如果客人在下午1:00之后退房,那么我希望加收50%的附加费。对于退房时间,我只使用当前的系统时间。简而言之,我试图在INSERT INTO查询中使用IF语句。但是,我一直在IF语句中遇到语法错误。我将如何格式化以消除任何语法错误?任何帮助将不胜感激。
SET IDENTITY_INSERT Billing OFF
INSERT INTO Billing (FolioID, BillingCategoryID, BillingDescription, BillingAmount, BillingItemQty, BillingItemDate)
VALUES(24
, 1
, 'Room'
, IF(CAST(GETDATE() as time) < '12:00 PM')
SELECT QuotedRate * Nights AS "TotalLodging"
FROM Folio
ELSE IF(CAST(GETDATE() as time) > '1:00 PM')
SELECT (QuotedRate * Nights) + ((QuotedRate * Nights) * .50) AS "TotalLodging"
FROM Folio
, 1
, GETDATE());
答案 0 :(得分:2)
你走了!这是你的SQL。
SET IDENTITY_INSERT Billing OFF
INSERT INTO Billing
(
FolioID
, BillingCategoryID
, BillingDescription
, BillingAmount
, BillingItemQty
, BillingItemDate
)
SELECT
24
, 1
, 'Room'
, CASE
WHEN CAST(GETDATE() AS TIME) <= '12:00' THEN QuotedRate * Nights
WHEN CAST(GETDATE() AS TIME) >= '13:00' THEN (QuotedRate * Nights) + (QuotedRate * Nights * .50)
ELSE (QuotedRate * Nights) + (QuotedRate * Nights * .50)
END
, 1
, GETDATE()
FROM Folio
WHERE FolioID = 24
SQL Fiddle已关闭,因此我创建了表并在本地运行SQL。见下文。
以下是各个SQL脚本。您可能想为IDENTITY列等修改它。
CREATE TABLE Billing (
FolioID INT NOT NULL,
BillingCategoryID INT NULL,
BillingDescription VARCHAR(100) NOT NULL,
BillingAmount DECIMAL(9,2) NULL,
BillingItemQty NUMERIC(5,0) NULL,
BillingItemDate DATETIME NULL
)
CREATE TABLE Folio
(
FolioID INT NOT NULL,
QuotedRate DECIMAL(6,2) NOT NULL,
Nights INT NOT NULL
)
INSERT INTO Folio(FolioID, QuotedRate, Nights)
VALUES (24, 100.00, 5)
INSERT INTO Billing (
FolioID
, BillingCategoryID
, BillingDescription
, BillingAmount
, BillingItemQty
, BillingItemDate
)
SELECT
24
, 1
, 'Room'
, CASE
WHEN CAST(GETDATE() AS TIME) <= '12:00' THEN QuotedRate * Nights
WHEN CAST(GETDATE() AS TIME) >= '13:00' THEN (QuotedRate * Nights) + (QuotedRate * Nights * .50)
ELSE (QuotedRate * Nights) + (QuotedRate * Nights * .50)
END
, 1
, GETDATE()
FROM Folio
WHERE FolioID = 24
SELECT * FROM Billing
我使用了FolioID = 24
,因为这就是我在INSERT
语句中看到的值。但是这种方法可以用于任何FolioID
以下条件将根据一天中的时间为您提供正确的计算。您还应该有一个默认子句“以防万一”,这是下面的ELSE
部分。
SELECT 'Total Lodging' =
CASE
WHEN CAST(GETDATE() AS TIME) <= '12:00' THEN QuotedRate * Nights
WHEN CAST(GETDATE() AS TIME) >= '13:00' THEN (QuotedRate * Nights) + ((QuotedRate * Nights) * .50)
ELSE (QuotedRate * Nights) + ((QuotedRate * Nights) * .50) -- Default rate
END
FROM Folio
我在SQL Server中使用了条件,没有从表中选择SELECT以确保我的CASE
语句有效,见下文。
答案 1 :(得分:-1)
INSERT INTO Billing (FolioID, BillingCategoryID, BillingDescription, BillingAmount, BillingItemQty, BillingItemDate)
VALUES(
24
, 1
, 'Room'
, CASE WHEN (CAST(GETDATE() as time) < '12:00 PM') then
(
SELECT QuotedRate * Nights AS "TotalLodging" FROM Folio
)
ELSE
(
SELECT (QuotedRate * Nights) + ((QuotedRate * Nights) * .50) AS "TotalLodging"
FROM Folio
)
End
, 1
, GETDATE()
)