ทดลองใช้ SQL ผ่าน Command line เพื่อทำ Task Backup/Restore ฉบับคนขี้เกียจรอ เริ่มแรกได้ข้อมูลจากที่เคยอ่านผ่านๆ ในบล๊อกต่างประเทศ ก็ไม่ได้สนใจอะไร จนมีพี่คนหนึ่งในกลุ่มนักวิชาการคอมพิวเตอร์ เขาได้จุดประกายให้ศึกษาการใช้ CLI อีกครั้ง เพราะเขาเองก็ใช้แบบนี้เหมือนกัน คือ เขียน Batch file เพื่อให้มันทำงานตามเวลาที่กำหนดไว้
(ซึ่งการทำงานของ Batch ทั้งหมดผมขอผ่านไป ของผมมีการเรียก vbs เพื่อทำ logs ด้วย)
จะแนะนำในส่วนของ OSQL หรือบางคนใช้ SQLCMD ก็ได้เหมือนกัน
OSQL -E -Q "RESTORE DATABASE <database> FROM DISK = '<file location>.bak' WITH REPLACE"
code ด้านบนก่อนหน้านี้ทดลองอยู่หลายวิธี ก็ run ไม่ได้ ลองใส่ -P -S -U ทุกวิธีแล้ว ก็ไม่ผ่าน เกิด error ว่า
Msg 3201, Level 16, State 1, Line 1
Cannot open backup device 'H:\Backup\HOMC.Bak'. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
ทดลองคำสั่ง restore ด้วยไฟล์ที่อยู่บนเครื่องตัวเอง
- สามารถใช้งานได้ แสดงว่า คำสั่งไม่ผิดพลาด
จึงคิดว่าปัญหาน่าจะเกิดจาก MAP NETWORK ที่ทำไว้มันจำกัดสิทธิ์การ write ข้อมูล
- เมื่อลองตรวจสอบดู พบว่าไม่ใช่ เมื่อให้ สิทธิ์ full control แล้วก็เป็นเช่นเดิม
วิธีแก้ปัญหาการ restore แบบข้ามเครื่อง ด้วยวิธีการดึงไฟล์ .bak นั้น ให้ใส่ remote path แบบเต็มๆ
- ใส่แบบนี้เลย \\servername\path\filename.bak
พบว่าสามารถใช้งานได้ และรวดเร็วกว่าการเปิด SQL Server Management Studio ถึง 2 เท่า!!
จากเดิมไฟล์ backup ขนาด 100G ใช้เวลา restore ประมาณ 30-40 นาที แต่เมื่อใช้ CLI เข้ามาช่วย ผม restore เสร็จภายในเวลา 20-25 นาทีเท่านั้น!!
คำอธิบายเพิ่มเติม
Basic OSQL syntax
OSQL is a command line tool that allows you to issue commands to Microsoft SQL Server. To run OSQL, simply bring up a DOS box and type OSQL followed by any required switches. You can view the complete OSQL command syntax with:
OSQL -?
This technical note describes only those switches required to perform the operations included in the note. Note: OSQL switches are case-sensitive. Switches:
- -S <sql-server-name> - the name of the SQL Server, including instance, if applicable. You may use "." (without quotes) if you are running OSQL on the same machine as SQL Server.
- -d <database-name> - the name of the database on which the operation is to be performed. For example -d ExpressDB.
- -U <user-name> - the SQL Server user account under which to run the specified command.
- -P <password> - the password associated with the specified user account.
- -E - use NT authentication to interact with SQL Server
- -Q "<SQL-command>" - the command to issue to SQL Server.
- -i <file-of-SQL-commands> - a file containing one or more commands to issue to SQL Server.
ป้ายกำกับ: cli, howto, mssql