dongtiandexue123456 2013-08-26 19:50
浏览 52
已采纳

在PHP中创建的多行批处理命令无法识别我声明的变量

My php class creates the following command:

INSERT INTO contacts (firstName, lastName) VALUES ('jon', 'snow') 
DECLARE @IDcontacts VARCHAR(200)
SET @IDcontacts = @@IDENTITY;

INSERT INTO emailAddresses (ownerId, emailAddress) VALUES (@IDcontacts, 'jon@thewall.com') 
INSERT INTO emailAddresses (ownerId, emailAddress) VALUES (@IDcontacts, 'jon@winterfell.com') 

INSERT INTO emailAddresses (ownerId, emailAddress) VALUES (@IDcontacts, 'thebastard@winterfell.com') 

I create the connection, begin a transaction with, and execute the batch with sqlsrv_query().

After executing the batch, sqlsrv_errors() gives me four errors: [Microsoft][SQL Native Client][SQL Server]Must declare the scalar variable "@IDcontacts".

however, if I use exactly the same batch string in SQL Server Management Studio, it works fine and all four records are inserted with the correct identity value from the first insert.

I'm using SQL Server Express 2005, php version 5.4.3 and the most recent sqlsrv driver. I haven't been able to find anything about this on technet or the ms forums, and any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongnao6858 2013-09-02 16:25
    关注

    In essence, as described in a response to this question on the MSDN forums, the SQL is not executed as a batch even when submitted as a single string. Each command is executed by sp_executesql, which makes every command run in a separate scope.

    I suppose I could use a global temporary table to do the same thing, but instead chose to rewrite the PHP to handle each command separately, handling transactions, errors, and backreferences after each command is attempted. I was hoping that wasn't true, but I am told it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误