SQL Server:过程表无法插入值null

时间:2015-12-09 00:45:00

标签: sql sql-server

我想在表格中添加100个存储空间。

这是我的程序:

CREATE PROCEDURE [add100*sTORAGE] 
AS
    DECLARE @i int, @start DATETIME, @end DATETIME

    SET @start = GETDATE()
    SET @i = 1

    WHILE @i < 101
    BEGIN
        INSERT INTO Storage(storage_name) 
        VALUES (CONCAT('Nume', CONVERT(nvarchar, @i)))

        SET @i = @i +1
    END

    SET @end = GETDATE()

    DECLARE @testID INT = (SELECT TOP 1 (TestRunID) 
                           FROM TestRuns 
                           ORDER BY TestRunID DESC)

    DECLARE @tableID INT = (SELECT tableID 
                            FROM Tables 
                            WHERE Name = 'Storage')

    INSERT INTO TestRunTables (TestRunID, TableID, StartAt, EndAt) 
    VALUES (@testID, @tableID, @start, @end)
GO

执行后出错:

  

Msg 515,Level 16,State 2,Procedure add100 * sTORAGE,第13行
  无法将值NULL插入列'TestRunID',表'OnlineShop.dbo.TestRunTables';列不允许空值。 INSERT失败。

当我查看表格时,它已创建了99列。

我在关系中有一些空表,这是它的插入(也许这是原因):

--INSERTS--

-- insert views into "Views"
INSERT INTO Views(Name) VALUES ('View1')
INSERT INTO Views(Name) VALUES ('View2')
INSERT INTO Views(Name) VALUES ('View3')

select * from views

delete from views where ViewID>1

-- insert into "Tests"
INSERT INTO Tests(Name) VALUES ('[add100*Storage-runView1-del100*Storage]')
INSERT INTO Tests(Name) VALUES ('[add100*Product-runView2-del100*Product]')
INSERT INTO Tests(Name) VALUES ('[add100*OrderProduct-runView3-    del100*OrderProduct]')

SELECT * FROM Tests

--insert into tables
INSERT INTO Tables(Name) VALUES ('Table1') 
INSERT INTO Tables(Name) VALUES ('Table2')
INSERT INTO Tables(Name) VALUES ('Table3')

SELECT * from Tables

-- insert into "testTable"
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES   (1,1,100,1)
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES (3,2,100,1)
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES (2,3,100,1)

SELECT * FROM TestTables

-- insert into "testViews"
INSERT INTO TestViews(TestID,ViewID) VALUES (1,1)
INSERT INTO TestViews(TestID,ViewID) VALUES (3,2)
INSERT INTO TestViews(TestID,ViewID) VALUES (2,3)

SELECT * FROM TestViews

怎么了?谢谢。

1 个答案:

答案 0 :(得分:2)

错误告诉你一切 - 表TestRunTables有列&#34; TestRunID&#34;这要求该字段具有值。您需要确保在该字段中插入值,或者更改列,以便在您不指定时使用默认值。

这一行:

DECLARE @testID INT = (SELECT TOP 1 (TestRunID) FROM TestRuns ORDER BY TestRunID DESC)
如果没有从TestRuns返回记录或第一个TestRunID为null,

将@testID设置为null。这可能是您需要解决的问题。