繁体   English   中英

通过添加值取决于另一列的新列来更改表

[英]Alter a Table by adding a new column whose value depends on another column

我有一个表SMTP (简体)

初期

| Id |    Server       | ConnectionRequired |
---------------------------------------------
| 0  | smtp.tea.com    |        '1'         |
| 1  | smtp.juice.com  |        '0'         |
| 2  | smtp.coffee.com |        NULL        |
| 3  | smtp.milk.org   |        '1'         |

ConnectionRequiredCHAR(1)

我正在尝试添加:

INT类型的ConnectionType

谁的初始值取决于ConnectionRequired

'1' becomes 1 otherwise it becomes 0

中间阶段

| Id |    Server       | ConnectionRequired | ConnectionType |
--------------------------------------------------------------
| 0  | smtp.tea.com    |        '1'         |       1        |
| 1  | smtp.juice.com  |        '0'         |       0        |
| 2  | smtp.coffee.com |        NULL        |       0        |
| 3  | smtp.milk.org   |        '1'         |       1        |

然后我要DROP ConnectionRequired

结束阶段

| Id |    Server       | ConnectionType |
----------------------------------------|
| 0  | smtp.tea.com    |       1        |
| 1  | smtp.juice.com  |       0        |
| 2  | smtp.coffee.com |       0        |
| 3  | smtp.milk.org   |       1        |

到目前为止,我有:

ALTER TABLE SMTP ADD ConnectionType INT NOT NULL

   MIDDLE STAGE.... HAPPENS HERE

ALTER TABLE SMTP DROP COLUMN ConnectionRequired

您在寻找中间阶段吗? 如果是这样,我会尝试

更新smtp设置connectionType =解码(connectionRequired,'1',1,0);

并同时工作(SQL Server和Oracle)

update smtp set connectionType = (case when connectionRequired = '1' then 1 else 0 end);

使用以下语句添加新列。

ALTER TABLE Table_Name
ADD ConnectionType INT 

使用以下语句更新该列。

UPDATE Table_Name
SET ConnectionType  = CASE WHEN ConnectionRequired = '1' 
                       THEN 1 ELSE 0 END

添加一列以更新数据似乎比必要的步骤更多。 我不确定这是否会减少日志记录,但似乎不太可能导致页面拆分并扩展表的大小(至少是暂时的)。

鉴于:

CREATE TABLE dbo.SMTP
(
  Id INT PRIMARY KEY,
  [Server] NVARCHAR(256),
  ConnectionRequired CHAR(1)
);

INSERT dbo.SMTP VALUES
(0,'smtp.tea.com   ','1' ),
(1,'smtp.juice.com ','0' ),
(2,'smtp.coffee.com',NULL),
(3,'smtp.milk.org  ','1' );

然后,您可以简单地首先更新数据(以消除NULL ):

UPDATE dbo.SMTP SET ConnectionRequired = '0' WHERE ConnectionRequired IS NULL;

还要确定数据不为'0''1'任何行要做什么:

SELECT * FROM dbo.SMTP WHERE ConnectionRequired NOT IN ('0','1');
-- UPDATE ...

然后更改数据类型和可为空性:

ALTER TABLE dbo.SMTP ALTER COLUMN ConnectionRequired INT NOT NULL;

并重命名该列:

EXEC sp_rename N'dbo.SMTP.ConnectionRequired', N'ConnectionType', N'COLUMN';

如果表包含数据,则not null在新列上使用not null 您将必须先创建它允许空值,然后运行“中间阶段”,然后更改not null约束。 但这将失败,因为ConnectionRequired为null。 您想如何处理这些?

对于中间阶段:使用

update SMTP set ConnectionType = cast(ConnectionType as int)

这会将'1' (字符)转换为1 (整数),将'0' (字符)转换为0 (整数),并将NULL (字符)转换为NULL (整数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM