我已经将我们的 Azure 云数据库设置为连接到我们的“SQL server 2008 R2”服务器的链接服务器,如下所述:http: //blogs.msdn.com/b/sqlcat/archive/2011/03/08 /linked-servers-to-sql-azure.aspx 我启用了 RPC 和 RPC Out,因为我在某处读到了它。
现在的问题是我无法获取刚刚插入的记录的 ID。请看一下这个测试表:
CREATE TABLE dbo.TEST
(
ID INT IDENTITY(1, 1) NOT NULL
CONSTRAINT PK_TEST_ID PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
我还创建了这个存储过程:
CREATE PROCEDURE test_create @ID INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO TEST
DEFAULT VALUES
SELECT @ID = SCOPE_IDENTITY()
END
我试图通过多种方式获取最后插入的值,但它们都不起作用:
DECLARE @ID INT
EXEC AZURE01.TestDB.dbo.test_create @ID OUTPUT
SELECT @ID
INSERT INTO AZURE01.TestDB.dbo.TEST DEFAULT VALUES
SELECT @ID = SCOPE_IDENTITY();
SELECT @ID
INSERT INTO AZURE01.TestDB.dbo.TEST DEFAULT VALUES
SELECT @ID = @@IDENTITY
SELECT @ID
SELECT * FROM OPENQUERY(AZURE01, 'INSERT INTO TestDB.dbo.TEST DEFAULT VALUES; SELECT SCOPE_IDENTITY() AS ID');
DECLARE @ScopeIdentity TABLE (ID int);
INSERT INTO @ScopeIdentity
EXEC AZURE01.master..sp_executesql N'
INSERT TestDB.dbo.TEST DEFAULT VALUES;
SELECT SCOPE_IDENTITY()';
SELECT * FROM @ScopeIdentity;
INSERT AZURE01.TestDB.dbo.TEST
OUTPUT inserted.ID
INTO @ScopeIdentity
DEFAULT VALUES
SELECT * FROM @ScopeIdentity
我理解为什么 SCOPE_IDENTITY() 和 @@IDENTITY 不起作用(因为它们是本地函数/变量,没有来自链接服务器的信息)但是带有输出参数的存储过程应该起作用,对吗?(在它工作的服务器上本地)
任何人?:-)