简体   繁体   English

更改表合并列T-SQL

[英]Alter table merge columns T-SQL

I need to alter the physical structure of a table. 我需要更改表的物理结构。

Combine 2 columns into a single column for the entire table. 将2列合并为整个表格的一列。

Eg 例如

ID  Code  Extension
1   012   8067978

Should be 应该

ID  Num
1   0128067978

You can just add them together in the select statement: 您可以在select语句中将它们添加在一起:

SELECT Column1 + Column2 AS 'CombinedColumn' FROM TABLE

To Permanently Add them together: 永久添加它们:

Step 1. Add Column : 步骤1. 添加列

   ALTER TABLE YOUR_TABLE
     ADD COLUMN Combined_Column_Name VARCHAR(15) NULL

Step 2. Combine fields 步骤2.合并字段

   UPDATE YOUR_TABLE
     SET Combined_Column_Name = Column1 + Column2

If you wanted to keep the table intact you could just access the table information through a view . 如果您想保持表完整无缺,则可以通过视图访问表信息。

CREATE VIEW View_To_Access_Table
AS
   SELECT t.Column1, t.Column2, etc....
           t.CombinedColumn1 + t.CombinedColumn2 AS 'CombinedColumnName'
   FROM YOUR_TABLE t

You could also create a computed column if you didn't want to create a view: 如果您不想创建视图,也可以创建一个计算列

ALTER TABLE YOUR_TABLE
  ADD COLUMN CombinedColumn AS Column1 + Column2
ALTER TABLE DataTable ADD FullNumber VARCHAR(15) NULL
GO

UPDATE DataTable  SET FullNumber = ISNULL(Column1, '') + ISNULL(Column2, '')
GO

-- you may have FullNumber as NOT NULL, if the number is mandatory and not null for every record
ALTER TABLE DataTable ALTER COLUMN FullNumber VARCHAR(15) NOT NULL

First step creates the column and the second makes the concatenation of strings, also taking care of null values, if any. 第一步创建列,第二步创建字符串的串联,还处理空值(如果有)。

Before dropping old columns, you should consider their usage. 在删除旧列之前,应考虑其用法。 If you need any of the numbers in some reports, it is harder to split the string than actually having the value stored. 如果在某些报告中需要任何数字,则比实际存储值更难拆分字符串。 However, this also implies redundancy (more space, possible consistency problems). 但是,这也意味着冗余(更多空间,可能的一致性问题)。

You can first combine the column into a single column then perform following steps:- 您可以先将该列合并为一个列,然后执行以下步骤:-

update table Column1 = ISNULL(Column1, '') + ISNULL(Column2, '')

rename the column and drop the extra column from table. 重命名该列,然后从表中删除多余的列。 make sure that the column have datatype as varchar. 确保该列的数据类型为varchar。

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

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