简体   繁体   English

INSERT INTO 导致列中出现空值

[英]INSERT INTO causing nulls in columns

I'm trying to concatenate two columns and add a comma and space between them in SQL Server 2014.我正在尝试在 SQL Server 2014 中连接两列并在它们之间添加逗号和空格。

Here's the code I'm using (redacting the table name for privacy reasons)这是我正在使用的代码(出于隐私原因编辑表名)

INSERT INTO Table (EntityName)
    SELECT CONCAT(MailingLine1, ', ', MailingState) 
    FROM Table

This is concatenating the strings correctly, but in the process, it's causing all other columns and all other rows to read as NULL and wipes the data from the table.这是正确连接字符串,但在此过程中,它导致所有其他列和所有其他行读取为 NULL 并从表中擦除数据。

There are roughly 30 columns that already have data within them大约有 30 列已经包含数据

Any thoughts?有什么想法吗?

If you are looking to add a new column with this function CONCAT(MailingLine1, ', ', MailingState) so you can use a computed column如果您希望使用此函数CONCAT(MailingLine1, ', ', MailingState)添加新列CONCAT(MailingLine1, ', ', MailingState)可以使用计算列

--if [EnityName]  already exists in the table you have to drop it first
alter table TABLE
drop column [EntityName]

alter table TABLE
add [EntityName] as CONCAT(MailingLine1, ', ', MailingState)

If you don't want to add a computed column you can follow @GordonLinoff answer (use UPDATE command)如果您不想添加计算列,您可以按照@GordonLinoff 的回答(使用 UPDATE 命令)


Else, If you are looking to insert new rows not to update rows, the issue is that you are only inserting values in EntityName column and ignoring all other columns, you can assign values as the following (assuming you have 3 columns)否则,如果您希望插入新行而不是更新行,问题是您仅在EntityName列中插入值而忽略所有其他列,您可以按如下方式分配值(假设您有 3 列)

Insert into Table (EntityName,EntityName2,EntityName3)

SELECT CONCAT(MailingLine1, ', ', MailingState),Value1,Value2 FROM Table

Where Value1,Value2 can be columns from the table, or fixed value ie 'John'其中Value1,Value2可以是表中的列Value1,Value2也可以是固定值,'John'

Set a default value for the other volums, a not NULL value.为其他卷设置一个默认值,一个非 NULL 值。 (See example) (见示例)

ALTER TABLE {table_name} ADD DEFAULT {dafault_value} FOR {column_name}

I'm guessing you want update , not insert :我猜你想要update ,而不是insert

update Table
    set EntityName = CONCAT(MailingLine1, ', ', MailingState);

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

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