2015-12-06 34 views
2

我正在使用DELETE語句的OUTPUT子句插入到歸檔表中。在azure sql中使用OUTPUT子句刪除語句

此代碼在我的本地數據庫上沒有問題。但是,我在Azure數據庫上運行時遇到錯誤,因爲列值爲空。

爲什麼Azure上的行爲會有所不同?

此代碼:

DECLARE @courseId uniqueidentifier 
SET @courseId = 'c7f5a926-e77a-4465-9120-38da284ed7d5' 

DECLARE @courseCode nvarchar(max) 
SELECT @courseCode = CourseCode FROM Courses WHERE CourseId = @courseId 

SELECT @courseId 
SELECT @courseCode 

-- Courses 
DELETE Courses 
OUTPUT DELETED.* 
INTO Archived_Courses 
WHERE CourseId = @courseId 

返回此錯誤:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

Msg 515, Level 16, State 2, Line 16 Cannot insert the value NULL into column 'CourseName', table '...dbo.Archived_Courses'; column does not allow nulls. INSERT fails. The statement has been terminated.

+1

您沒有向我們展示表格定義 - 您是否自己檢查過它們?另外,我們沒有任何數據 - 您確定您正在使用相同的表定義*和*本地計算機和Azure之間的足夠類似的數據? –

+0

稍後再仔細檢查。假設Azure SQL支持帶輸出子句的刪除語句,那麼表上的不同聚簇索引會導致此行爲? – TonE

+1

你是對的 - 有一長串列和兩列的位置切換。這引發了一個進一步的問題:是否在OUTPUT DELETED。*子句中指定列名 - 對此有何看法? – TonE

回答

1

我做了不到原始,究竟是誰的工作非常好我的SQL Azure數據庫: 假設你有類似的東西:

Create Table Courses 
(
    CourseId uniqueidentifier NOT NULL PRIMARY KEY DEFAULT newid(), 
    CourseCode nvarchar(50) NOT NULL DEFAULT newid(), 
    CourseDescription nvarchar(MAX) NULL 
) 

Create Table Archived_Courses 
(
    CourseId uniqueidentifier NOT NULL PRIMARY KEY , 
    CourseCode nvarchar(50) NOT NULL , 
    CourseDescription nvarchar(MAX) NULL 
) 

而這裏是你的解決方案,這對我有效(只有區別,我ge用一個簡單的選擇在球場上的代碼)

Insert into Courses (CourseCode, CourseDescription) values ('MOD01', 'Module 1 description'); 

DECLARE @courseId uniqueidentifier 
Select @courseId = CourseId from Courses where CourseCode = 'MOD01' 

DECLARE @courseCode nvarchar(max) 
SELECT @courseCode = CourseCode FROM Courses WHERE CourseId = @courseId 

SELECT @courseId 
SELECT @courseCode 

-- Courses 
DELETE Courses 
OUTPUT DELETED.* 
INTO Archived_Courses 
WHERE CourseId = @courseId 

確定t是唯一identiefier,你不必在你的內部部署數據庫插入產生的任何默認值,你不要對你的天青SQL數據庫?

Sébastien

+0

問題是由於列順序切換爲兩列。感謝您確認OUTPUT子句在Azure上按預期工作。 – TonE

+0

(我不確定你上面的示例代碼應該分配一個newid()到Courses.CourseCode列) – TonE