[英]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.