[英]Stored procedure that Selects, Conditions, sets variables, then inserts/updates into a table
我想知道這種存儲過程是否可行,我是否需要某種循環結構或其他東西? 我想這樣做,基本上是按以下順序進行的:
如果可以的話,請問我能得到一些草稿嗎? 感謝您的閱讀! 請嘗試幫助! 這是我在想的另一種“圖表”:
感謝到目前為止的所有嘗試!如果我弄清楚了,我將其發布。
我們需要更多信息,但我將為您提供98%或更高的賠率,它們可以全部通過兩個查詢(一個用於插入,一個用於更新)來完成。
這是插入的通用示例:
INSERT INTO [Table2]
SELECT
t1.[col1], /* use columns from table1 to update table2 */
COALESCE(t3.[col2], t1.[col2]) /* table3 "overrides" table1 */
FROM [Table1] t1 -- get all rows from table1
LEFT JOIN [Table3] t3 ON t3.ID = t1.Table3ID
LEFT JOIN [Table2] t2 ON t2.ID = t1.Table2ID
WHERE t2.OtherColumn IS NULL /* insert - only make changes where the record doesn't already exist */
和更新:
UPDATE t2
SET t2.[col1] = t1.[col1],
t2.[col2] = COALESCE(t3.[col2], t1.[col2])
FROM [table1] t1
LEFT JOIN [Table3] t3 ON t3.ID = t1.Table3ID
INNER JOIN [Table2] t2 ON t2.ID = t1.Table2ID /* update - only make changes where the record does already exist */
沒有關於數據模型的更多信息很難說,但是有些情況與您描述的情況類似,無需迭代即可處理。
例如,您可以選擇t1和t3的左連接,如果存在t3值則使用t3值,或者使用基於t1列值的表達式。 這是一個粗略的示例。
insert into t2 (column list)
Select case when t3.Column is not null then t3.Column
when t1.Column = 'somevalue' then 'someothervalue'
else...(other conditions/values) end
...
from t1 left join t3 on t1.Key = t3.Key
(增加有關您的具體情況的詳細信息會提高獲得幫助的質量)
我將大開眼界,並假設您正在談論MS SQL Server。
是的,這種事情是可能的。 以下是一些偽代碼,可幫助您入門:
declare @someTable (
idx int identity(1,1),
column1 type,
column2 type,
etc type )
declare @counter
set @counter = 1
insert into @someTable (column1, column2, etc)
select column1, column2, etc from table1
while @counter < (select max(idx) from @someTable)
begin
-- loop through records and perform logic
insert result into table3
set @counter = @counter + 1
end
如果可能的話...嘗試使用單個查詢。 連接表並使用Case語句執行邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.