在执行插入之前检查现有行
表 1 列:
诊所代码、日程安排日期、日程安排时间、来源 ID
表2 列:
诊所代码、日程安排日期、日程安排时间
有一个存储过程可以执行以下操作:
1.删除Table1中所有clinic_code='ABC' AND Schedule_date=xyz的记录 2. 将 table2 中 table2.clinic_code='ABC' AND table2.schedule_date=xyz 的所有记录插入到 table1 中。
我想更改第 2 步。
*2.插入 table2 中 table2.clinic_code='ABC' AND table2.schedule_date=xyz 的所有记录,但不要覆盖 table1 中 source_id=2 的那些行。
这是步骤 2 中的原始插入语句:
INSERT INTO table1 (col1, col2, col3)
SELECT table2.col1, table3.col2, table2.col3
FROM table2
INNER JOIN table3 ON table2.col3 = table3.col5 AND etc...
表名称和附加列已被省略,如果有帮助,我可以输入确切的列数。
Table1 columns:
clinic_code, schedule_date, schedule_time, source_id
Table2 columns:
clinic_code, schedule_date, schedule_time
There is a stored procedure that does:
1. Delete all records in Table1 where clinic_code='ABC' AND schedule_date=xyz
2. INSERT all records from table2 where table2.clinic_code='ABC' AND table2.schedule_date=xyz into table1.
I want to make a change in step 2.
*2. INSERT all records from table2 where table2.clinic_code='ABC' AND table2.schedule_date=xyz, but don't overwrite those rows in table1 where source_id=2.
Here's the original insert statement in step 2:
INSERT INTO table1 (col1, col2, col3)
SELECT table2.col1, table3.col2, table2.col3
FROM table2
INNER JOIN table3 ON table2.col3 = table3.col5 AND etc...
Table names, and additional columns have been left out, if it would be helpful, I can put the exact number of columns.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定我是否完全遵循,因为如果您将行插入到 table1 中,则 table1.col3 还没有这些行的值。如果您只是想避免 table1.col3 = 2,您可以使用这样的 where 子句:
这将避免将值 2 插入到 table1.col3 中,因为 table2.col3 是您从中提取该值的位置。如果我错过了这里的要点,请告诉我,但这应该可以了。
编辑 - 鉴于您已经说过 table1 和 table2 之间的记录相似,并且假设您可以在两个表之间加入一列,您可以执行如下操作:
想法是您现在已将 table1 包含在您的SELECT 等也可以将其包含在 WHERE 子句中。 (如果其他 SQL 风格的别名语法已关闭,请原谅我,我在 T-SQL 方面经验丰富。)
I'm not sure I follow completely, because if you're inserting the rows into table1, table1.col3 won't have a value for those rows yet. If you just want to avoid having table1.col3 = 2, you could use a where clause like this:
Which would avoid inserting the value 2 into table1.col3, since table2.col3 is where you're pulling that from. If I'm missing the point here let me know, but that should do it.
EDIT - given that you've said the records between table1 and table2 are similar, and assuming there's a column you could join on between the two tables, you could do something like this:
The idea being that you've now included table1 in your SELECT and as such can also include it in your WHERE clause. (Forgive me if the aliasing syntax is off for other SQL flavors, I'm mostly experienced in T-SQL.)
好吧,我不知道你使用的是哪种 SQL,所以这里是一个标准的 SQL 脚本:
Well I don't know which SQL you are using so here is a standard SQL script: