将IP地址转换为INSERT到SQL Server 2012的字符串

时间:2014-10-08 15:44:31

标签: sql powershell insert sql-server-2012

如果我在SQL Server 2012上运行以下命令,则可以正常运行

BEGIN
  IF NOT EXISTS (SELECT *
                 FROM dbo.Computers
                 WHERE Computer_ID = 'A1E8AC100AFB160500BAD934ACD97536')
  BEGIN
    INSERT INTO dbo.Computers(Date_of_Record, Computer_Name, IP_Address, Operating_System, Agent_Version, BIOS_Version, Computer_ID)
    VALUES (CAST(GETDATE() AS DATE), 'LPB0FLYX', '10.10.10.10', 'Windows 7 Enterprise Edition', '12.1.2015.2015', 'LENOVO - 6040000 Phoenix BIOS SC-T v2.2', 'A1E8AC100AFB160500BAD934ACD97536')
  END
END

但是,如果我在Powershell中运行以下内容($k[1]的值为10.10.10.10),则无效

$SQL_UPDATE = "BEGIN
                      IF NOT EXISTS (SELECT *
                                     FROM dbo.Computers
                                     WHERE Computer_ID = $k[5])
                      BEGIN
                          INSERT INTO dbo.Computers(Date_of_Record, Computer_Name, IP_Address, Operating_System, Agent_Version, BIOS_Version, Computer_ID)
                          VALUES (CAST(GETDATE() AS DATE), $k[0], $k[1], $k[2], $k[3], $k[4], $k[5])
                      END
                  END

这是我创建的表的结构

enter image description here

如何将$k[1]强制转换为字符串,这样我才能传递'10 .10.10.10'

修改

这是$ SQL_UPDATE的回声

BEGIN
                      IF NOT EXISTS (SELECT *
                                     FROM dbo.Computers
                                     WHERE Computer_ID = 9D2838890AFB16050170A8AEE4F15517)
                      BEGIN
                          INSERT INTO dbo.Computers(Date_of_Record, Computer_Name, IP_Address, Operating_System, Agent_Version, BIOS_Version, Computer_ID)
                          VALUES (CAST(GETDATE() AS DATE), LMG0033SZ, 10.10.10.10, Windows 7 Enterprise Edition, 12.1.4013.4013, LENOVO - 1180 LENOVO BIOS Rev: FNKT24A 0.0, 9D2838890AFB16050170A8AEE4F15517)
                      END
                  END

错误:

Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near 'D2838890AFB16050170A8AEE4F15517'.
Incorrect syntax near '.194'."
At D:\Script\unknowns.ps1:259 char:5
+     $cmd_update.executenonquery()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException

1 个答案:

答案 0 :(得分:1)

问题是您在生成的SQL中缺少字符串引号。

如果您可以控制要包含的值(即,它们不包含单引号),您只需在字符串中添加引号即可;

...
VALUES (CAST(GETDATE() AS DATE), '$k[0]', '$k[1]', '$k[2]', '$k[3]', '$k[4]', '$k[5]')
...