sqlstringt-sqlxp-cmdshell

How to separate a result of one column into multiple columns in T-SQL?


I am trying to to get information about disk drives, their total space and free space (3 columns total). I found a query in the web similar to my needs but that query required some modifications. I did them but got stuck then. I can't obtain middle column. Can you help me with that?

create table #mainDOScmd (ExecCommand NVARCHAR(500))
insert into #mainDOScmd
EXEC master..xp_cmdshell 'wmic LOGICALDISK where "DriveType=3" get DeviceID, FreeSpace, Size';
select * from #mainDOScmd
CREATE TABLE #TEMP( 
[DriveLetter] VARCHAR(100),
[TotalDriveSpace(GB)] NVARCHAR(500), 
[FreeSpaceOnDrive(GB)] NVARCHAR(500)
)
INSERT INTO #TEMP
SELECT 
LEFT(ExecCommand, PATINDEX('%  %',ExecCommand)),
LTRIM(RIGHT(ExecCommand,LEN(ExecCommand)-PATINDEX('%  %',ExecCommand))), --problematic part
LTRIM(RIGHT(LTRIM(RIGHT(ExecCommand,LEN(ExecCommand)-PATINDEX('%  %',(ExecCommand)))), LEN(LTRIM(RIGHT(ExecCommand,LEN(ExecCommand)-PATINDEX('%  %',(ExecCommand))))) - PATINDEX('%  %',LTRIM(RIGHT(ExecCommand,LEN(ExecCommand)-PATINDEX('%  %',REVERSE(ExecCommand))))))) 
FROM #mainDOScmd
WHERE ExecCommand IS NOT NULL AND RTRIM(LEFT(ExecCommand, PATINDEX('%  %',ExecCommand))) <> 'DeviceID'
select * from #TEMP
DROP TABLE #TEMP
DROP TABLE #mainDOScmd
GO

Solution

  • Here is a quick solution. Just replace last column value by nothing from your problematic part

    CREATE TABLE #mainDOScmd (ExecCommand NVARCHAR(500))
    
    INSERT INTO #mainDOScmd
    EXEC master..xp_cmdshell 'wmic LOGICALDISK where "DriveType=3" get DeviceID, FreeSpace, Size';
    
    SELECT *
    FROM #mainDOScmd
    
    CREATE TABLE #TEMP (
        [DriveLetter] VARCHAR(100)
        ,[TotalDriveSpace(GB)] NVARCHAR(500)
        ,[FreeSpaceOnDrive(GB)] NVARCHAR(500)
        )
    
    INSERT INTO #TEMP
    SELECT LEFT(ExecCommand, PATINDEX('%  %', ExecCommand))
        ,replace(LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', ExecCommand))), ' ' + LTRIM(RIGHT(LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', (ExecCommand)))), LEN(LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', (ExecCommand))))) - PATINDEX('%  %', LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', REVERSE(ExecCommand))))))), '')
        ,LTRIM(RIGHT(LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', (ExecCommand)))), LEN(LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', (ExecCommand))))) - PATINDEX('%  %', LTRIM(RIGHT(ExecCommand, LEN(ExecCommand) - PATINDEX('%  %', REVERSE(ExecCommand)))))))
    FROM #mainDOScmd
    WHERE ExecCommand IS NOT NULL
        AND RTRIM(LEFT(ExecCommand, PATINDEX('%  %', ExecCommand))) <> 'DeviceID'
    
    SELECT *
    FROM #TEMP
    
    DROP TABLE #TEMP
    
    DROP TABLE #mainDOScmd