How do I get just the value of the field name?

78 Views Asked by At

I'm trying to use sqlcmd utility and the query is working I'm just wondering how I can get just the value without fieldname and those dashes?

$res = sqlcmd -Q @"
    :Connect . 
    use [Database1]

    select firstname from customer
"@

$res

Output:

firstname                                         
--------------------------------------------------
John

enter image description here

2

There are 2 best solutions below

5
Nick Abbot On BEST ANSWER

You need -h -1, -m 1 and set nocount on; Try this:

$res = sqlcmd -S . -m 1 -h -1 -Q @"
    use [Database1];
    set nocount on;
    select firstname from customer;
"@
0
lit On

PowerShell is about automation using types. sqlcmd.exe goes back to parsing text strings. sqlcmd.exe doesn't know types from Shinola.

Use Invoke-Sqlcmd. It will even give back the value as the correct type, not just always string.

(Invoke-Sqlcmd -ServerInstance DEVDW02 -Query "SELECT firstname FROM customer;").firstname

((Invoke-Sqlcmd -ServerInstance DEVDW02 -Query "SELECT firstname FROM customer;").firstname).GetType()