Inserting null values when using bulk insert

回眸只為那壹抹淺笑 提交于 2019-12-25 18:29:48

问题


I have one table:

CREATE TABLE cust (
    cust_id NOT NULL,
    cust_name NOT NULL,
    address NULL
);

I have to insert these rows into another table:

CREATE TABLE 1cust_det (
    cust_id NOT NULL,
    cust_name NOT NULL,
    address NOT NULL
);

Unfortunately the cust.address column contains NULL values. I want to insert these rows from cust to 1cust_det using a cursor. What do I have to do?


回答1:


INSERT INTO
    cust_det
SELECT
    cust_id,
    cust_name,
    COALESCE(address, 'UNKNOWN')
FROM
    cust



回答2:


If you have access to change the destination table, just add a default to the column.

CREATE TABLE 1cust_det (
cust_id NOT NULL,
cust_name NOT NULL,
address NOT NULL DEFAULT 'DEFAULT_VALUE');

or if you can edit the existing destination table and it doesnt get drooped

ALTER TABLE 1cust_det
ALTER address SET DEFAULT 'DEFAULT_VALUE'

The easiest way if you don't have control of the destination table to add a default value to the address column is to use a case statement in the insert itself. In the example below you can also use a ISNULL evaluation, but you might want to search for empty strings as well. Please try to find a better way to insert instead of using a cursor.

INSERT dbo.1cust_det
    (cust_id,cust_name,[address]) 
SELECT cust_id,cust_name,
    CASE 
        WHEN [address] IS NULL THEN 'some default value'
        ELSE [address]
    END AS [address]
FROM cust



回答3:


Above answers are correct. You may have another table that may have address for cust_id. Join that table to get missing address. I have seen that in almost all databases, address is stored for every customer. You must get address where address is NULL in the table cust.



来源:https://stackoverflow.com/questions/24373208/inserting-null-values-when-using-bulk-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!