在sql server中将null插入整数字段时出现问题

iq0todco  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(395)

在使用可为null的整数构建动态插入查询时,出现以下错误:

CREATE TABLE TestTable(
    [my_id] [bigint] NOT NULL,
    [so_id] [int] NULL
)

CREATE TABLE TestTable2(
    [my_id] [bigint] NOT NULL,
    [so_id] [int] NULL
)

DECLARE @so_id AS   int;
DECLARE @my_id  AS INT;
declare @my_sql as nvarchar(max);

INSERT INTO TestTable (my_id, so_id)  VALUES (1, NULL); --so_id might be null or 0,1,2

set @my_id = (SELECT top 1 my_id FROM TestTable);
SET @so_id = (SELECT top 1 so_id FROM TestTable);

SET @my_sql = 'INSERT INTO TestTable2 (my_id, so_id) VALUES (' + CAST(@my_id AS varchar(MAX)) +  ',  NULL )'    --if so_id is null insert null into TestTable2

EXEC sp_executesql @my_sql

SELECT * FROM TestTable2

SET @my_sql = 'INSERT INTO TestTable2 (my_id, so_id) VALUES (' + CAST(@my_id AS varchar(MAX)) +  ', ' + ISNULL(@so_id, 'NULL') + ')'    --if so_id is null insert null into TestTable2

EXEC sp_executesql @my_sql

DROP TABLE TestTable
DROP TABLE TestTable2

我得到一个错误:
将varchar值insert转换为testtable2(my\u id,so\u id)值(1)到数据类型int时,转换失败。

9o685dep

9o685dep1#

试试这个:

SET @my_sql = 'INSERT INTO TestTable2 (my_id, so_id) VALUES (' + CAST(@my_id AS varchar(MAX)) +  ', ' + ISNULL(CAST(@so_id AS VARCHAR), 'NULL') + ')'    --if so_id is null insert null into TestTable2
ibrsph3r

ibrsph3r2#

使用参数!

SET @so_id = (SELECT top 1 so_id FROM TestTable);

SET @my_sql = '
INSERT INTO TestTable2 (my_id, so_id)
    VALUES (@my_id,  NULL )';

EXEC sp_executesql @my_sql,
                   N'@my_id int',
                   @my_id = @my_id;

当然,对于这一点,动态sql是愚蠢的,因为您可以:

INSERT INTO TestTable2 (my_id, so_id)
    SELECT TOP 1 so_id, NULL
    FROM TestTable;

而且,使用 SELECT TOP 没有 ORDER BY .

qv7cva1a

qv7cva1a3#

在您试图插入的最后一条sql语句中 'NULL' 转换为int列。一种解决方案是从insert中完全省略null字段,因为在insert期间省略时值将为null。

SET @my_sql = 'INSERT INTO TestTable2 (my_id'
                +CASE WHEN @so_id IS NULL THEN ')' ELSE ',so_id) 'END
                +'  VALUES (' + CAST(@my_id AS varchar(MAX)) +  ''
                +CASE WHEN @so_id IS NULL THEN ')' ELSE ','+CAST(@so_id AS nvarchar(20))+') ' END

相关问题