Powershell SQL Insert,参数获取错误

时间:2017-03-30 22:07:38

标签: sql .net powershell

我试图在我的PS脚本中创建参数化插入语句,并且我一直收到有关转换nvarchar的错误:

异常调用" ExecuteNonQuery"用" 0"参数:"转换nvarchar值时转换失败'(从端点选择e.endpointid e m.meterid = e.meterid中的内连接米m,其中m.meterno =' 06700& #39;)'数据类型int。"。

这是我的剧本的相关部分:

 $linesplit = $line -split ","
 $prefix = "$($linesplit[0]),$($linesplit[1]),$($linesplit[2]),$($linesplit[3])"
 $numberOfMeters = $linesplit.length - 4 
 for($i = 1; $i -le $numberOfMeters; $i++){
     $meternumber = $linesplit[3 + $i]
     $meternumber = "'"+$meternumber+"'"
     $notecontent = "'"+$prefix+"'"
     $endpointid = "(select e.endpointid from endpoints e inner join meters m on m.meterid=e.meterid where m.meterno ="+$meternumber+" )"
                     write-host $endpointid -fore Cyan
     $userid = "55"
     $created = "(select GETDATE())"
     $notetype = "0"
     $note = $notecontent
         write-host $note -fore Cyan
     $sqlinsert = "
         insert into endpointnotes (endpointId, userId, created, noteType, note)
         VALUES (@endpointid,@userid,@created,@notetype,@note)
         "

         # Connect to SQL database and run insert statement
         $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
         $SqlConnection.ConnectionString = "server=$Server;database=$CSDatabase;uid=;pwd="
         $SqlConnection.open()
         $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
         $SqlCmd.Parameters.Add("@endpointid", $endpointid)
         $SqlCmd.Parameters.Add("@userid", $userid)
         $SqlCmd.Parameters.Add("@created", $created)
         $SqlCmd.Parameters.Add("@notetype", $notetype)
         $SqlCmd.Parameters.Add("@note", $note)
         $SqlCmd.CommandText = $sqlinsert
         $SqlCmd.Connection = $SqlConnection
         $SqlCmd.ExecuteNonQuery()
         $SqlConnection.close()
         }

甚至可以在我的一个参数中使用SELECT语句吗? 任何帮助将不胜感激!

由于

0 个答案:

没有答案