我已将HTML表从this site转换为XML文件。
我正在尝试在PowerShell中运行SQL查询,以将数据从XML文件复制到数据库表。如果我在SSMS中运行查询,它运行正常。但是,当我尝试在Powershell中运行以下代码时,我得到:
错误:输入查询太长
[string] $dbCommand =
@"
Truncate table DB_NAME.dbo.SQL_LIFE_CYCLE_UPLOAD_IC
DECLARE @Data XML
SELECT @Data = BulkColumn
FROM OPENROWSET(BULK 'D:\Powershell\Temp\SQL_Life_Cycle.XML', SINGLE_BLOB) AS x
INSERT INTO DB_NAME.dbo.SQL_LIFE_CYCLE_UPLOAD_IC
(PRODUCT_RELEASED,LIFECYCLE_START_DATE,MAINSTREAM_SUPPORT_END_DATE,EXTENDED_SUPPORT_END_DATE,SERVICE_PACK__SUPPORT_END_DATE,NOTES)
Select max(case when col=1 then value else '' end) as PRODUCT_RELEASED,
max(case when col=2 then value else '' end) as LIFECYCLE_START_DATE,
max(case when col=3 then value else '' end) as MAINSTREAM_SUPPORT_END_DATE,
max(case when col=4 then value else '' end) as EXTENDED_SUPPORT_END_DATE,
max(case when col=5 then value else '' end) as SERVICE_PACK__SUPPORT_END_DATE,
max(case when col=6 then value else '' end) as NOTES
from
(SELECT
x.y.value('Col[1]', 'int') AS [Col],
x.y.value('Row[1]', 'int') AS [Row],
x.y.value('Value[1]', 'VARCHAR(200)') AS [Value]
FROM @data .nodes('//DocumentElement/TableData') AS x ( y )
) rawTableData
group by row
having row >0
order by row
"@
OSQL.EXE -E -Q $dbCommand
有关如何重写此脚本的任何建议吗?
答案 0 :(得分:1)
我假设它太长,因为您使用OSQL.exe
并将其作为command line parameter
传递。看到你正在使用powershell
我只会使用内置的.net功能并以这种方式执行查询。如果您需要更多信息,只需在互联网上搜索.net SQL
ExecuteNonQuery
即可获得大量结果。
它的基础知识如下:
# Instantiate new SqlConnection object.
$Connection = New-Object System.Data.SQLClient.SQLConnection
# Set the SqlConnection object's connection string to the passed value.
$Connection.ConnectionString = "place a connection string here"
# Open the connection to the database.
$Connection.Open()
# Instantiate a SqlCommand object.
$Command = New-Object System.Data.SQLClient.SQLCommand
# Set the SqlCommand's connection to the SqlConnection object above.
$Command.Connection = $Connection
# Set the SqlCommand's command text to the query value passed in.
# this is where you pass the query string you wrote to
$Command.CommandText = $dbCommand
# Execute the command against the database without returning results (NonQuery).
$Command.ExecuteNonQuery()
# Close the currently open connection.
$Connection.Close()
我已经编写了几次这段代码,但我只是从这个脚本中获取它,可以在Microsoft的Technet库https://gallery.technet.microsoft.com/scriptcenter/Perform-ExecuteNonQuery-a05eb40a
中找到