Can I Use Order by to sort Stored Procedure results?

Viewed 44215

Simply, I have this SQL statment:

EXEC xp_cmdshell 'tasklist' 

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

Thanks,

4 Answers

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

Related