Cra*_*ein 4 sql-server powershell
尝试使用 powershell删除现有表
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server(".\CEF_2014_1")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("tempdb")
#drop the Table
$tb = new-object Microsoft.SqlServer.Management.Smo.Table($db, "listeningport")
$tb.Drop()
Run Code Online (Sandbox Code Playgroud)
但出现错误
PS C:\Users\craig.efrein\Dropbox\Scripts\Powershell> .\drop_table.ps1
Exception calling "Drop" with "0" argument(s):
"Drop failed for Table 'dbo.listeningport'. "
At C:\Users\craig.efrein\Dropbox\Scripts\Powershell\create_table.ps1:11 char:11
+ $tb.Drop <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Run Code Online (Sandbox Code Playgroud)
如果我先创建表,然后删除它,那就行了。
我是否正确填充了 $tb 对象?
$tb = new-object Microsoft.SqlServer.Management.Smo.Table($db, "listeningport")
Run Code Online (Sandbox Code Playgroud)
作为第二个问题,如何在 powershell 中删除表之前检查表是否存在?
一种更简洁的方法是直接从数据库对象中获取表对象,然后在它返回非 null 时将其删除。这只会在表存在时运行。
#drop the Table
$tb = $db.Tables['listeningport']
IF ($tb)
{$tb.Drop()}
Run Code Online (Sandbox Code Playgroud)
您可以使用$tb.Tables['tablename', 'schemaname']来使用非dbo架构。
当我在 SMO 中处理这样的事情时,我的偏好总是直接从父对象获取子对象。它更清晰,下一个阅读代码的人更清楚你在做什么(你直接从 db 对象中的表集合中获取表),并且很容易在一个步骤中检查是否存在。
对于您的特定问题,由于您正在查看tempdb. 你确定它有那个特定的名字吗?