简体   繁体   中英

Insert empty string into INT column for SQL Server

A SAMPLE table has only one column ID of type int , default null.

In Oracle when I do:

  insert into SAMPLE (ID) values ('');

the new record is added with blank value. But in SQL Server 2008, when I run the same insert statement, the new record has the value of 0.

Is there a way to force SQL Server 2008 to default blank string to NULL instead of 0 (for numerical type of columns)?

请改用NULL。

insert into SAMPLE (ID) values (NULL);

假设您的INSERT语句是在应用程序的许多位置重用的存储过程的一部分(或者,可能是批处理总是由客户端代码的相同部分构造),并且插入的值是作为传递的数字传递的数字字符串参数,您可以像这样修改INSERT:

INSERT INTO SAMPLE (ID) VALUES (NULLIF(@argument, ''));

How about another idea - define an INSTEAD OF INSERT Trigger .

Despite the fact that you're trying to insert a string, with this the operation is "intercepted", empty string is replaced by NULL, and the insert succeeds.

If you define this trigger on your table, then you can continue to insert empty string as before, with no other changes.

Edit: As Martin Smith points out, this effectively is a comparison to 0 (the equivalent of empty string as an int) meaning you won't be able to store 0 in this table. I leave this answer here in case that's acceptable to your situation - either that or re-do all your queries!

CREATE TRIGGER EmptyStringTrigger
ON [SAMPLE]
INSTEAD OF INSERT
AS
  BEGIN
      INSERT INTO [SAMPLE](ID)
      SELECT CASE
               WHEN ID = '' THEN NULL
               ELSE ID
             END
      FROM   inserted
  END

SQL Fiddle example

You can't insert a 'string' into a int column. Oracle must be just handling that for you.

Just try inserting NULL if that's what you need.

insert into SAMPLE (ID) values (NULL);

还有一个选择

insert into SAMPLE (ID) values (DEFAULT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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