0

I have a data in Excel that want to insert into SQL.

There are rows that have a blank, when I try to insert the data into SQL, the data is inserted as '0' instead of 'NULL'.

Example of data as below:

---------------------------------
Items          Total      Price
---------------------------------
Glue             4          $1
Socks            2          $7
Tumbler                     $40
Pen             10          $1
Eraser                      $0.5
---------------------------------

Items(char(50))
Total(int)
Price(float)

Does anyone know how can I insert the blank data as NULL instead of "0" ?

Below is what I have so far.

STRSQL = "INSERT INTO [Stationary].[dbo].[Stocks] ([Items],[Total],[Price])" & _
"VALUES ('" & Range("A" & i) & "','" & Range("B" & i) & "','" & Range("C" & i) & "')"

Really appreciate if anyone can help me on this.

2
  • allow null for total(int) column Commented Aug 28, 2020 at 8:48
  • Depending on risk and value of the database, you might also want to sanitise/escape the data you read from the cells to avoid malicious SQL injection. Commented Aug 28, 2020 at 9:25

1 Answer 1

1

Please, try replacing

& Range("B" & i) &

with

& IIf(Range("B" & i).value = "", "'Null'", Range("B" & i).value) &
Sign up to request clarification or add additional context in comments.

2 Comments

This should work perfectly. One small enhancement, consider using value2 in place of value, to protect against the (perhaps unlikely) scenario where someone messes with the formatting of that column on you. But, this enhancement is not mandatory.
@NAJAA BAZILAH: Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.