根据另一列的值使列接收0或1

时间:2016-11-09 14:01:40

标签: sql-server

我想知道是否可以在表格中创建一个列,根据同一个表中另一列的值自动获取它们的值,下面的例子说明:

CREATE TABLE dbo.example
(
    m_id INT NOT NULL CONSTRAINT PK_mid PRIMARY KEY IDENTITY (1,1),
    m_name NVARCHAR(30) NOT NULL,
    m_startdate DATE NOT NULL CONSTRAINT CHK_startdate CHECK(m_startdate <= SYSDATETIME()),
    m_enddate DATE CONSTRAINT CHK_enddate CHECK(m_enddate <= SYSDATETIME()),
    m_status INT CONSTRAINT CHK_status CHECK(m_status = 0 or m_status = 1)
)

如果m_enddate为null,我想让m_status接收0,如果它不为null,则为1。这当然是插入一行。

3 个答案:

答案 0 :(得分:5)

您可以按如下方式使用计算列...

 CREATE TABLE dbo.example
(
m_id INT NOT NULL CONSTRAINT PK_mid PRIMARY KEY IDENTITY (1,1),
m_name NVARCHAR(30) NOT NULL,
m_startdate DATE NOT NULL CONSTRAINT CHK_startdate CHECK(m_startdate <= SYSDATETIME()),
m_enddate DATE CONSTRAINT CHK_enddate CHECK(m_enddate <= SYSDATETIME()),
m_status AS CASE
    WHEN m_enddate is null THEN 0 ELSE 1 
    END 
)

答案 1 :(得分:2)

迈克尔建议的计算列最好,但如果您无法更改表格,那么您可以为此查看。

autocommit

现在你可以做到

CREATE VIEW dbo.vwExample AS
  SELECT m_id,
         m_name,
         m_startdate,
         m_enddate,
         CASE WHEN m_enddate is null THEN 0 ELSE 1 END as m_status
  FROM   dbo.example

并且它将具有m_status的正确值,而不必更改表本身。

答案 2 :(得分:1)

在T-SQL中,您可以使用而不是插入/更新触发器,它允许您拦截插入和更新并注入逻辑。

CREATE TRIGGER dbo.exampleInsertTrigger
   ON   [dbo].[example]
   INSTEAD OF INSERT
AS 
BEGIN
INSERT INTO [dbo].[example]
    ([m_name]
    ,[m_startdate]
    ,[m_enddate]
    ,[m_status])
SELECT
    [m_name]
    ,[m_startdate]
    ,[m_enddate]
    ,CASE
    WHEN [m_enddate] is null THEN 0 ELSE 1 
    END
FROM inserted
END


CREATE TRIGGER dbo.exampleUpdateTrigger
   ON   dbo.example
   INSTEAD OF UPDATE
AS 
BEGIN
UPDATE [dbo].[example]
    SET
    [m_name] = inserted.[m_name]
    ,[m_startdate] = inserted.[m_startdate]
    ,[m_enddate] = inserted.[m_enddate]
    ,[m_status] = CASE
    WHEN inserted.[m_enddate] is null THEN 0 ELSE 1 
    END
FROM inserted
WHERE inserted.[m_id] = [dbo].[example].[m_id]
END