Thank this author by sharing:
By Brian Knight,
2003/11/14 (first published: 2001/05/03)
The xp_cmdshell procedure allows the DBA to execute any operating
system command via TSQL. One can, for example notify users that the
SQL Server will be stopping by running the following command:
The no_output parameter after the procedure will make the results
of the net send command invisible to the ISQL window. The output that is not suppressed is displayed as a varchar (255) datafield.
Xp_cmdshell becomes more challenging when you want to make the command you wish to run
a variable. The following is an excerpt from sp_axeusers (for SQL Server 6.5):
-- .... OMITTED DECLARE STATEMENTS ....
-- CREATE TEMPORARY TABLE FOR SP_WHO TO POPULATE
create table #usrkill (
-- INSERT INTO TEMP TABLE
insert into #usrkill exec sp_who
-- PREPARING VARIABLES FOR NET SEND
SELECT @NOTIFYMSG1 = '"NET SEND '
SELECT @NOTIFYMSG2 = ' YOUR SESSION WILL DISCONNECT IN 30 SECONDS'
SELECT @NOTIFYMSG3 = '"'
-- BEGIN CURSOR
DECLARE CNOTIFYUSR SCROLL CURSOR FOR
SELECT DISTINCT HOSTNAME from #usrkill where dbname = @USRDB
FETCH FIRST FROM CNOTIFYUSR into @hostname
select @NOTIFYSTATE = @NOTIFYMSG1 + @hostname
+ @NOTIFYMSG2 + @NOTIFYMSG3
exec master..xp_cmdshell @NOTIFYSTATE, no_output
--... Omit rest of code
--... Full code is at : ftp://downloads.swynk.com/sp_axeusers.SQL
As you can see above, to place strings inside a xp_cmdshell command, you will have to string
the variables together like @NOTIFYSTATE.
Before you begin implementation of this extended stored procedure into your
applications, you will need to be aware of the security issues. When executing xp_cmdshell, you will have the same rights and permissions
as whichever NT account is configured to start SQL Server (MSSQLSERVER service). This account is generally either
an administrator or system account. In either case, you pose a substantial security risk if you don't lock down the extended stored procedure to not allow your non-sa users to execute it.
Trying to run bcp. Not sure if it is an xp_cmdshell issue or the bcp line
Save result ofa xp_cmdshell command
Never Ending xp_cmdshell stored procedure