Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I'm trying to get column names with data types (and lengths) for SQL Server instance using PowerShell. I got this far:

#Load PSSnapin
Add-PSSnapin *SQL*

#Get column names
$colNames = dir 'SQLSERVER:\SQL\MYCOMPUTER\MYSQLINSTANCE\Databases\MYDATABASE\Tables' | 
    Where-Object {$_.DisplayName -match "dbo.MYTABLE"} | 
        ForEach-Object {$_.Columns} |
            Select-Object Name, DataType
$colNames

How to get also datatype lengths for columns?

share|improve this question

migrated from stackoverflow.com Oct 3 '11 at 11:36

This question came from our site for professional and enthusiast programmers.

add comment

2 Answers 2

up vote 3 down vote accepted

The lengths are found at <Column>.Properties['Length'].Value, so you can select it like:

#Get column names
$colNames = dir 'SQLSERVER:\SQL\MYCOMPUTER\MYSQLINSTANCE\Databases\MYDATABASE\Tables' | 
    Where-Object {$_.DisplayName -match "dbo.MYTABLE"} | 
        ForEach-Object {$_.Columns} |
            Select-Object Name, DataType, `
                @{Name='Length'; Expression = {$_.Properties['Length'].Value}}
$colNames
share|improve this answer
add comment

Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:

SELECT 
    TableName = OBJECT_NAME(c.OBJECT_ID), 
    ColumnName = c.name,
    DataType = t.name,
    MaxLength = t.max_length
FROM 
    sys.columns AS c
JOIN 
    sys.types AS t 
ON c.user_type_id=t.user_type_id
WHERE 
    OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.