【问题标题】:How to change all of the columns in a table to NULL if they are emptyHow to change all of the columns in a table to NULL if they are empty
【发布时间】:2022-12-27 20:22:44
【问题描述】:

I'm importing a lot of data from an excel file using the SSIS package. Thus, Excel contains some empty columns. I'd like to make it Null.

I'm now updating a blank column to NULL using the query below.

UPDATE TT 
SET DEATHDATE = NULL
FROM TEMP_TABLE TT 
WHERE LTRIM(RTRIM(DEATHDATE)) = ''

UPDATE TT 
SET CURRENTDATE= NULL
FROM TEMP_TABLE TT 
WHERE LTRIM(RTRIM(CURRENTDATE)) = ''

UPDATE TT 
SET City = NULL
FROM TEMP_TABLE TT 
WHERE LTRIM(RTRIM(City )) = ''

OR

UPDATE TT 
SET BIRTHDATE = NULL
FROM TEMP_TABLE TT 
WHERE DATALENGTH(BIRTHDATE) = 0

This update statement will update toNULLif the specified column records areEMPTY.

But I don't like doing this. I want to change all of the records in the table. If there areEMPTYrecords in that table, I want to change them toNULL.

Is that even possible? Thank you in advance

【问题讨论】:

  • You have to specify each column you want to update. And I'd probably do a separate UPDATE for each column.
  • Why are these apparent dates even strings?
  • @HoneyBadger I'm using the SSIS package to import data from an excel file. so i import the date types as NVARCHAR

标签: sql sql-server


【解决方案1】:

You can combine all these into a single update, using a CASE to decide whether to overwrite the value or not.

UPDATE TT 
SET DEATHDATE   = CASE WHEN TRIM(DEATHDATE)   = '' THEN NULL ELSE DEATHDATE END,
    CURRENTDATE = CASE WHEN TRIM(CURRENTDATE) = '' THEN NULL ELSE CURRENTDATE END,
    BIRTHDATE   = CASE WHEN TRIM(BIRTHDATE)   = '' THEN NULL ELSE BIRTHDATE END
FROM TEMP_TABLE TT 
WHERE TRIM(DEATHDATE) = ''
  OR  TRIM(CURRENTDATE) = ''
  OR  TRIM(BIRTHDATE) = '';

You calso shorten the expressions to CASE WHEN TRIM(DEATHDATE) <> '' THEN DEATHDATE END etc, but I think the above is clearer.

Quite why you are storing dates in a text column is a different question. All I can say is: don't.

【讨论】:

  • I'm using the SSIS package to import data from an excel file. If I select the dates data type, certain records won't insert properly.
  • I suggest you fix the databeforeyou import it
  • I tried, but I couldn't find a way to fix the data before importing it.
猜你喜欢
  • 2019-06-27
  • 2022-12-02
  • 2022-12-01
  • 2022-12-02
  • 2022-12-16
  • 2022-12-01
  • 2022-12-01
  • 2022-12-02
  • 2022-12-02
相关资源
最近更新 更多