我正在运行以下内容:Windows 7,Python 2.5和SQL Server 2005,SQLNCLI作为提供程序。我有一个表,它的名称是TABLE,其字段是FIELD0,FIELD1,FIELD2。
您可以在此处找到SQLNCLI.msi:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en
我正在考虑使用商店程序。它的目的是更新一行,如果它不存在则插入它。 当它到达插入语句时出错,但插入成功。这是代码:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
create procedure [dbo].[TEST0]
@FIELD0 varchar(200)
as
begin
declare @exist varchar(MAX)
set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0)
if @exist is null
begin
insert into [TABLE] ([FIELD0],[FIELD1],[FIELD2]) values (@FIELD0,'FIELD1','FIELD2')
select top 1 [FIELD0] from [TABLE]
where
[FIELD0] = @FIELD0
return 10
end
else
select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0
end
要查看错误,请运行此Python代码两次;它第一次失败,但第二次成功:
from win32com.client import Dispatch
dbConn = Dispatch( "ADODB.Connection" )
dbConn.Open( "server=xx.xx.xx.xx; initial catalog=MYDB; user=myuser; password=mypass; provider=SQLNCLI" )
command = Dispatch( 'ADODB.Command' )
command.ActiveConnection = s.dbConn
command.CommandText = "[TEST0]"
command.CommandType = 4
param0 = command.CreateParameter ('@FIELD0',200,1,200,'VALUE')
command.Parameters.Append( param0 )
print param0
(rs, result) = command.Execute()
while not rs.EOF:
dic = {}
for field in rs.Fields :
dic[str( field.name )] = str( field.value )
print dic
rs.MoveNext()
答案 0 :(得分:0)
我解决了这个问题:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
alter procedure [dbo].[TEST0]
@FIELD0 varchar(200)
as
begin
set nocount on <=============================add this
declare @exist varchar(MAX)
set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0)
if @exist is null
begin
insert into [TABLE] ([FIELD0],[FIELD1],[FIELD2]) values (@FIELD0,'FIELD1','FIELD2')
select top 1 [FIELD0] from [TABLE]
where
[FIELD0] = @FIELD0
end
else
select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0
set nocount off <=============================add this
end