32

Simply, I have this SQL statment:

EXEC xp_cmdshell 'tasklist' 

can we order or filter the results by using order by or where?

Thanks,

Wael Dalloul
  • 22,172
  • 11
  • 48
  • 57

4 Answers4

23

I checked jamietre link, and this is the complete answer:

Create table  #MyTempTable
(output varchar(max))

INSERT INTO #MyTempTable
EXEC xp_cmdshell 'tasklist' 

select * from #MyTempTable where output like 'ie%' order by output 

Thanks for all...

Wael Dalloul
  • 22,172
  • 11
  • 48
  • 57
17

You need to output the results into a temporary table first. This should show you how to do it

Insert results of a stored procedure into a temporary table

Community
  • 1
  • 1
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
3

not directly. You can insert exec into a temp table or table variable and then sort that though

chuck taylor
  • 2,476
  • 5
  • 29
  • 46
2

When running the above query multiple times, you might run into this error: There is already an object named '#MyTempTable' in the database.

To mitigate this you can use a DROP IF EXISTS statement as follows before creating the temp table.

IF OBJECT_ID(N'tempdb..#MyTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyTempTable
END
CREATE TABLE #MyTempTable
(OUTPUT VARCHAR(max))

INSERT INTO #MyTempTable
EXEC xp_cmdshell 'tasklist' 

SELECT * FROM #MyTempTable WHERE OUTPUT like 'ie%' ORDER BY OUTPUT

Aage
  • 5,932
  • 2
  • 32
  • 57