Chào các bạn,
Cường xin giới thiệu một lệnh đơn giản về BCP kết hợp với xp_cmdshell để xuất dữ liệu từ SQL ra file dạng text nhanh chóng.
Việc này rất có ích khi bạn có nhu cầu lấy dữ liệu theo định kỳ. Ví dụ hằng ngày lúc 08h dữ liệu chấm công sẽ tự động xuất ra file và lưu trữ trên thư mục share nào đó và hệ thống tính lương sẽ lấy các dữ liệu này tính toán v.v.v
declare @lstrSQL_Run nvarchar(1000)
set @lstrSQL_Run = ‘bcp “SELECT name from sysobjects” queryout D:\XXX.SQL -w -T’
exec master.dbo.xp_cmdshell @lstrSQL_Run
Ví dụ câu TSQL trên mình sẽ lấy tên object trong database và xuất ra file xxx.sql tại ổ đĩa D
=> Nếu khi chạy TSQL trên báo lỗi này
Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1
SQL Server blocked access to procedure ‘sys.xp_cmdshell’ of component ‘xp_cmdshell’
because this component is turned off as part of the security configuration for this server.
A system administrator can enable the use of ‘xp_cmdshell’ by using sp_configure.
For more information about enabling ‘xp_cmdshell’, search for ‘xp_cmdshell’ in SQL Server Books Online.
Thì bạn bật Shell Command lên nhé sau đó chạy lại TSQL trên
EXEC sp_configure ‘show advanced options’, 1
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sp_configure ‘xp_cmdshell’, 1
GO
RECONFIGURE WITH OVERRIDE
GO