SQL Server Import Wizard treats NULL as literal string 'NULL'

[亡魂溺海] 提交于 2019-12-23 17:59:32

问题


When I attempt to import a .csv comma-delimited flat file into a Microsoft SQL server 2008R2 64-bit instance, for string columns a NULL in the original data becomes a literal string "NULL" and in a numeric column I receive an import error. Can anyone please help???


回答1:


Put the data into a staging table and then insert to the production table using SQL code.

update table1
set field1 = NULL
where field1 = 'null'

Or if you want to do for a lot of fields

update table1
    set field1 = case when field1 = 'null' then Null else Field1 End
      , field2 = case when field2 = 'null' then Null else Field2 End
      , field3 = case when field3 = 'null' then Null else Field3 End



回答2:


KISS

Pre-process it, Replace all "NULL" with "".

ie the .csv file will have

,,

Instead of

NULL,NULL,

Seems to do the job for me.




回答3:


Adding to HLGEM's answer, I do it dynamically, I load into staging table here all column types are VARCHAR and then do:

DECLARE @sql VARCHAR(MAX) = '';
SELECT @sql = CONCAT(@sql, '
    UPDATE [staging].[',[TABLE_NAME],']
    SET [',[COLUMN_NAME],'] = NULL
    WHERE [',[COLUMN_NAME],'] = ''NULL'';
    ')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE [TABLE_SCHEMA] = 'staging' 
    AND [TABLE_NAME] IN ('MyTableName');
SELECT @sql;
EXEC(@sql);

Then do:

INSERT INTO [dbo].[MyTableName] ([col1], [col2], [colN])
SELECT [col1], [col2], [colN]
FROM [staging].[MyTableName]

Where table [dbo].[MyTableName] is defined with the desired column types, this also fails and tells you in type conversion errors...



来源:https://stackoverflow.com/questions/17351099/sql-server-import-wizard-treats-null-as-literal-string-null

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