我想知道这种存储过程是否可行,我是否需要某种循环结构?我想这样做,基本上按照这个顺序:
如果可以的话,我可以在答案中得到某种草稿吗? 谢谢你的阅读! PLZ试着帮忙! 这是我正在思考的另一种“图表”:
感谢到目前为止的所有尝试!!如果我想到这一点,我会发布它。
答案 0 :(得分:2)
我们需要更多信息,但我会给你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 */
答案 1 :(得分:1)
如果没有关于您的数据模型的更多信息,很难说,但有些情况类似于您描述的可以在没有迭代的情况下处理的情况。
例如,您可以选择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
(关于您的具体情况的详细信息会提高您获得帮助的质量)
答案 2 :(得分:1)
我要跳枪并假设你在谈论MS SQL Server。
是的,这种事情是可能的。这里有一些psuedo代码可以帮助你入门:
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语句来执行逻辑。