SQL Server的示例表。是否可以在創建時插入外鍵值?
- MainRecords(
id, record
) - AuxRecords(
mainRecords_id, record
) - SourceRecords(
record1, record2
)
MainRecords.id
是自遞增的主身份密鑰。
是否有可能從SourceRecords
選擇並插入MainRecords
和AuxRecords
同時使得MainRecords.record = record1
,AuxRecords.record = record2
和AuxRecords.mainRecords_id = MainRecords.id
都在一個單獨的語句?
編輯:
基於從下面的提示,我想這...
DECLARE @MainRecords table(id int PRIMARY KEY IDENTITY, record varchar(5))
DECLARE @AuxRecords table(mainRecords_id int, record varchar(5))
DECLARE @SourceRecords table(record1 varchar(5), record2 varchar(5))
INSERT @SourceRecords VALUES ('a', 'a')
INSERT @SourceRecords VALUES ('a', 'b')
INSERT @SourceRecords VALUES ('a', 'c')
INSERT @SourceRecords VALUES ('b', 'a')
INSERT @SourceRecords VALUES ('b', 'b')
INSERT @SourceRecords VALUES ('b', 'c')
INSERT @SourceRecords VALUES ('c', 'a')
INSERT @SourceRecords VALUES ('c', 'b')
INSERT @SourceRecords VALUES ('c', 'c')
INSERT INTO @MainRecords (record)
OUTPUT inserted.id, @SourceRecords.record2
INTO @AuxRecords (mainRecords_id, record)
SELECT record1 FROM @SourceRecords
select * from @MainRecords
select * from @AuxRecords
但不幸的是得到錯誤:
Msg 137, Level 16, State 1, Line 16
Must declare the scalar variable "@SourceRecords".
如果我改變這些表類型的變量轉化爲現實表我得到的錯誤:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "SourceRecords.record2" could not be bound.
下面的工作很好,但顯然它不是一個完整的解決方案。我只是展示它來證明我的語法是正確的。
INSERT INTO @MainRecords (record)
OUTPUT inserted.id --, @SourceRecords.record2
INTO @AuxRecords (mainRecords_id) --, record)
SELECT record1 FROM @SourceRecords
所以...除非有一些竅門我缺少的,好像OUTPUT
是這個問題的一個死衚衕的解決方案。
使用觸發器創建視圖或空表的其他建議不是解決此問題的「單一語句」解決方案。此外,它們增加了默默無聞,而添加一些額外的列和使用存儲過程同樣複雜,但更明顯和直接。
爲什麼 「*在一條語句*」?只需在Transactions中使用存儲過程,無論如何你都應該這樣做。 – RBarryYoung
OUTPUT子句可能能夠爲您工作。你並沒有提供足夠的模式信息。通過'OUTPUT',您通常可以返回一個結果集,插入/更新/刪除一個表,並在同一個語句中插入另一個表中。列可用性存在限制。在事務中編寫多個語句要容易得多,但是,即使這樣做,'OUTPUT'語句對於捕獲一組生成的標識也是必需的。 –
@RBarryYoung與交易的過程是「我應該如何做這些事情」*如果沒有更優雅的方式。恕我直言,單一聲明*可以*,在理論上,更優雅。我編輯了我的問題,以表明我有多接近一個非常優雅的解決方案,但不幸的是,它似乎不起作用。此外,除非使用遊標或臨時表,或添加一些新的列等,否則您會看到您建議的內容不適用於我的精確示例;與我所希望的相比,這一切都有點混亂,但似乎是唯一的選擇。 –