简体   繁体   English

Shell脚本从Oracle DB表中删除记录

[英]Shell script to delete records from Oracle DB table

I have a situation where I need to run a shell script every 30 days to delete records from Oracle database table. 我遇到一种情况,我需要每30天运行一次shell脚本,才能从Oracle数据库表中删除记录。

The table has a column 'updated_date'. 该表具有“ updated_date”列。 I need to write a query to delete records where 'updated_date' less than current date minus 30 days. 我需要编写一个查询来删除'updated_date'少于当前日期减去30天的记录。

In Java I can do it comfortably. 在Java中,我可以轻松地做到这一点。 How to calculate the dynamic date and pass it to SQL query in Unix shell script. 如何计算动态日期并将其传递给Unix shell脚本中的SQL查询。

Can someone please help me. 有人可以帮帮我吗。

You could use the delete statement suggested by Littlefoot to utilize the system date from within the database. 您可以使用Littlefoot建议的delete语句来利用数据库中的系统日期。

But, since you asked - 但是,既然您问-

How to calculate the dynamic date and pass it to SQL query in Unix shell script, 如何计算动态日期并将其传递给Unix shell脚本中的SQL查询,

This is how you can do it. 这就是您可以做到的。

First, use the date command to get the current date in 'yyyy-mm-dd' format. 首先,使用date命令以'yyyy-mm-dd'格式获取当前日期。

export dt=$(date +%Y-%m-%d)

You may then use the date variable within your shell script in sqlplus . 然后,您可以在sqlplus的Shell脚本中使用date变量。

sqlplus -s userid/passwd@db_server<<EOF
delete from yourtable
      where updated_date < DATE '${dt}' - 30;
commit;
exit
EOF

That would be something like this: 那将是这样的:

delete from your_table
where updated_date < trunc(sysdate) - 30;

SYSDATE is a function that returns current date (and time - that's why I used TRUNC function which will remove time component). SYSDATE是一个返回当前日期的函数(和时间-这就是为什么我使用TRUNC函数将删除时间分量)。 It also means that you don't have to calculate date and pass it to SQL query - Oracle know it itself. 这也意味着您不必计算日期并将其传递给SQL查询 -Oracle本身就知道。

Though, note that SYSDATE shows database server date, so - if you work on different time zones, you might need to consider that fact. 但是,请注意,SYSDATE显示数据库服务器日期,因此-如果您在不同的时区工作,则可能需要考虑这一事实。

Also, "minus 30 days": is it always 30 days, or did you actually mean "minus 1 month"? 另外,“减30天”:是总是30天,还是您实际上是指“减1个月”? If so, you'd change the condition to 如果是这样,您可以将条件更改为

where updated_date < add_months(trunc(sysdate), -1)

and it'll take care about number of days in a month (30, 31; including February as well as leap years). 并且会考虑一个月中的天数(30、31;包括2月以及well年)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM