预置条件:
使用sa帐号登录SQL Server Management Studio,右键点击安全性-登录名-数据库用户名属性,设置服务器角色为sysadmin。
删除已存在的存储过程
String JOB_BCP_DELETE_SQL = “IF EXISTS (SELECT * FROM sys.objects WHERE name = 'PROCEDURE_BCP_OUT' AND type in (N'P', N'PC')) DROP PROCEDURE PROCEDURE_BCP_OUT ”; pre = conn.prepareStatement(JOB_BCP_DELETE_SQL); pre.execute();
创建存储过程
String sql = "set @sql = N'BCP ' + @tableName + ' out ' + @filePath + ' -c -t -U "' + @userName + '" -P "' + @password + '" -S "' + @dbIp + '"' "; StringBuffer createSqlBuf = new StringBuffer(); createSqlBuf.append("CREATE PROCEDURE PROCEDURE_BCP_OUT ") .append("@dbIp nvarchar(256), ") .append("@userName nvarchar(256), ") .append("@password nvarchar(256), ") .append("@tableName nvarchar(256), ") .append("@filePath nvarchar(256) ") .append("AS ") .append("BEGIN ") .append("EXEC master.sys.sp_configure 'show advanced options', 1 ") .append("RECONFIGURE ") .append("EXEC master.sys.sp_configure 'xp_cmdshell', 1 ") .append("RECONFIGURE ") .append("declare @sql nvarchar(256) ") .append(sql) .append("EXEC master..xp_cmdshell @sql ") .append("EXEC master.sys.sp_configure 'show advanced options', 1 ") .append("RECONFIGURE ") .append("EXEC master.sys.sp_configure 'xp_cmdshell', 0 ") .append("RECONFIGURE ") .append("END"); String createSql = createSqlBuf.toString(); pre = conn.prepareStatement(createSql); pre.execute();
执行存储过程
StringBuffer execSqlBuf = new StringBuffer(); execSqlBuf.append("EXECUTE PROCEDURE_BCP_OUT ") .append("@dbIp=?, ").append("@userName=?, ").append("@password=?, ") .append("@tableName=?, ").append("@filePath=?"); String execSql = execSqlBuf.toString(); pre = conn.prepareStatement(execSql); pre.setString(1, dbIp); pre.setString(2, dbUserName); pre.setString(3, dbPassword); pre.setString(4, tableName); pre.setString(5, file); pre.execute();