存储过程,选择,条件,设置变量,然后插入/更新到表
问题描述:
我想知道这种存储过程是否可能,我需要某种循环结构或什么?我想这样做,基本上是按照以下顺序:存储过程,选择,条件,设置变量,然后插入/更新到表
- 从一个表或视图中获取所有行。 (table1)
- 基于表1的列,我想设置变量以用于插入/更新table2。
- 我想引用另一个表(表3),从表1中找到一个将“覆盖”的关键字,以及行数据可能落入的任何情况。
- 插入或更新table2。
如果这是可能的,我可否在答案中得到某种草案? 谢谢您的阅读!请尝试帮助! 这里还有一个排序的 “图” 的我在想什么:。
- SELECT * FROM表1
- 情况下[表1] [table1column] - [表1] [table1column] < = 0,参数1 = “一个”(许多情况下)
- 情况下[表1] [TABLEID]表3中存在,参数1 = [表3] [参数]
- 情况下[表1] [TABLEID]是否存在于表2,更新,否则插入
感谢您的所有尝试到目前为止!!如果我想出来,我会发布它。
答
。
是的,那种事情是可能的。这里有一点伪代码,让你开始:
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语句来执行逻辑。
答
我们需要更多的信息,但是我会给你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值(如果存在)或使用基于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
哪个RDBMS?MySQL的? SQL Server? – 2009-08-13 15:10:24
你能用不同的方式来描述你的问题吗?我发现有点难以理解每一步的目标,特别是第3步。添加更多的细节也有助于给你一个更具体的答案。 – 2009-08-13 15:14:16
您是否考虑过在单个SQL语句中执行此操作?根据你的描述,这可能不需要带循环的存储过程,这取决于你需要做什么的细节。 – Chi 2009-08-13 15:14:40