web-dev-qa-db-ja.com

PowerShellを使用してデータ型(および長さ)のテーブル列を取得する方法

PowerShellを使用して、SQL Serverインスタンスのデータ型(および長さ)を含む列名を取得しようとしています。私はこれを手に入れました:

#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

列のデータ型の長さも取得するにはどうすればよいですか?

2
jrara

長さは<Column>.Properties['Length'].Valueにあるため、次のように選択できます。

#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

残念ながら、PowerShellの構文はわかりませんが、必要なSQLは次のとおりです。

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

DirtyPawsに感謝します。 Powershell構文を使用したSQLステートメント:

#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.