您可以使用多種approuches做到這一點:
計算列
CREATE TABLE t3
(
ID INT IDENTITY(1,1),
ApprovalID INT,
Approval AS (CASE
WHEN ApprovalID = 1 THEN 'Hatchery'
WHEN ApprovalID = 2 THEN 'Purchase'
WHEN ApprovalID = 3 THEN 'Rearing'
WHEN ApprovalID = 4 THEN 'Source Unknown'
WHEN ApprovalID = 5 THEN 'Not Approved'
ELSE '<Unknown approval state>'
END
) PERSISTED
)
INSERT INTO t3(ApprovalID) VALUES(1)
INSERT INTO t3(ApprovalID) VALUES(2)
INSERT INTO t3(ApprovalID) VALUES(3)
INSERT INTO t3(ApprovalID) VALUES(4)
INSERT INTO t3(ApprovalID) VALUES(5)
UPDATE t3
set ApprovalID = 2
where ApprovalID = 1
SELECT * FROM t3
觸發器
DROP TABLE t3
CREATE TABLE t3
(
ID INT IDENTITY(1,1),
ApprovalID INT,
Name NVARCHAR(256),
)
GO
CREATE TRIGGER t3_trigger
ON t3
AFTER INSERT, UPDATE
AS
UPDATE t3
SET Name = CASE
WHEN i.ApprovalID = 1 THEN 'Hatchery'
WHEN i.ApprovalID = 2 THEN 'Purchase'
WHEN i.ApprovalID = 3 THEN 'Rearing'
WHEN i.ApprovalID = 4 THEN 'Source Unknown'
WHEN i.ApprovalID = 5 THEN 'Not Approved'
ELSE '<Unknown approval state>'
END
FROM t3 INNER JOIN inserted i ON t3.ID = i.ID
GO
INSERT INTO t3(ApprovalID) VALUES(1)
INSERT INTO t3(ApprovalID) VALUES(2)
INSERT INTO t3(ApprovalID) VALUES(3)
INSERT INTO t3(ApprovalID) VALUES(4)
INSERT INTO t3(ApprovalID) VALUES(5)
UPDATE t3 set ApprovalID = 2 WHERE ApprovalID = 1
SELECT t3.*, Approval.Name FROM t3 LEFT JOIN Approval ON t3.ApprovalID = Approval.ApprovalID
但最好的方法是分割數據在兩個表
CREATE TABLE t3
(
ID INT IDENTITY(1,1),
ApprovalID INT,
)
CREATE TABLE Approval
(
ApprovalID INT,
Name NVARCHAR(256)
)
INSERT INTO Approval(ApprovalID, Name) VALUES(1, 'Hatchery')
INSERT INTO Approval(ApprovalID, Name) VALUES(2 , 'Purchase')
INSERT INTO Approval(ApprovalID, Name) VALUES(3, 'Rearing')
INSERT INTO Approval(ApprovalID, Name) VALUES(4, 'Source Unknown')
INSERT INTO Approval(ApprovalID, Name) VALUES(5, 'Not Approved')
INSERT INTO t3(ApprovalID) VALUES(1)
INSERT INTO t3(ApprovalID) VALUES(2)
INSERT INTO t3(ApprovalID) VALUES(3)
INSERT INTO t3(ApprovalID) VALUES(4)
INSERT INTO t3(ApprovalID) VALUES(5)
並使用選擇數據查詢象下面這樣:
SELECT t3.*, Approval.Name FROM t3 LEFT JOIN Approval ON t3.ApprovalID = Approval.ApprovalID
你真的應該有一個存儲ApprovalIDs和他們的名字一個表,然後針對它 – Lamak
執行'JOIN'你會以錯誤的方式去做。您應該將'approval'列提取到另一個具有兩列的靜態表,即'approval_id'和'approval',並且在想要顯示「批准」字符串時對原始表使用'join'。這個過程被稱爲[規範化](http://en.wikipedia.org/wiki/Database_normalization)。 – Mureinik
計算列在這裏是正確的選擇,因爲「批准」是「ApprovalID」的直接翻譯。您可以創建UDF來轉換值並將該udf用作列「批准」定義。 –