web-dev-qa-db-fra.com

Comment obtenir des colonnes de table avec des types de données (et des longueurs) à l'aide de PowerShell?

J'essaie d'obtenir des noms de colonnes avec des types de données (et des longueurs) pour l'instance SQL Server à l'aide de PowerShell. Je suis aussi loin:

#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

Comment obtenir des longueurs de type de données pour les colonnes?

2
jrara

Les longueurs se trouvent à <Column>.Properties['Length'].Value, vous pouvez donc le choisir comme:

#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
5
Rynant

Malheureusement, je ne connais pas la syntaxe PowerShell, mais, Heres, le SQL pour ce que vous voulez:

SELECT 
    TableName = OBJECT_NAME(c.OBJECT_ID), 
    ColumnName = c.name,
    DataType = t.name, -- Type is an int in the columns table, this returns the type name.
    MaxLength = c.max_length -- Returns the max length of the column.
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'
4
DirtyPaws

Merci à Dirtypaws. Déclaration SQL avec Syntaxe PowerShell:

#Credentials
$SQLServer = "SQL ServerName/IP Address"
$SQLDBName = "DatabaseName"
$uid ="MySqlUser"
$pwd = "MySqlUserPassword"

#Establish SQL Connection
$connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()

#Create SQL Statement
$query = "
SELECT 
    TableName = OBJECT_NAME(c.OBJECT_ID), 
    ColumnName = c.name,
    DataType = t.name, -- Type is an int in the columns table, this returns the type name.
    MaxLength = c.max_length -- Returns the max length of the column.
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) = 'MyTableName'
"

#Add SQL Query to SQL Connection
$command = $connection.CreateCommand()
$command.CommandText = $query

#Execute SQL Query
$result = $command.ExecuteReader()

#Add result to DataTable Object and Display it
$table = new-object “System.Data.DataTable”
$table.Load($result)

Write-Host ($table | Format-Table | Out-String)
Write-Host ($table | Format-List | Out-String)
2
Jonathan H.