Sql-Server

如何使用 PowerShell 獲取具有數據類型(和長度)的表列?

  • June 25, 2021

我正在嘗試使用 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

如何獲得列的數據類型長度?

長度位於<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

不幸的是,我不知道 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'

引用自:https://dba.stackexchange.com/questions/6437