4

现在,我正在尝试摆脱 delphi 程序中的一些旧搜索代码,并且我想将搜索推送到程序正在使用的 sql-server。为此,我创建了这个查询,它与我在不同 C# 程序中使用的查询非常相似。

使用 SQL Management Studio 或从 C# 程序查询可以正常工作,但使用 Delphi 我得到“未从查询返回光标”错误。

这是查询

DECLARE @SearchString NVARCHAR(MAX);
SET @SearchString = ':Param1';
IF @SearchString = '' SET @SearchString = '%';

--Table for splitted values
DECLARE @SearchItms TABLE
(
Item NVARCHAR(MAX)
)

--Split Operator
DECLARE @SplitOn NVARCHAR(MAX)
SET @SplitOn = ' '; --Split Keywords on space

--Splitting
While (Charindex(@SplitOn,@SearchString)>0)
Begin
    Insert Into @SearchItms (Item)
    Select ('%' + Substring(@SearchString,1,Charindex(@SplitOn,@SearchString)-1) + '%')

    Set @SearchString = Substring(@SearchString,Charindex(@SplitOn,@SearchString)+1,len(@SearchString))
End

--Add last Item
Insert Into @SearchItms (Item) 
Select ('%' + @SearchString + '%')

--Select fitting items
SELECT MyTable.*
FROM MyTable INNER JOIN SecondTable ON (MyTable.Key = SecondTable.Key)
WHERE
NOT EXISTS(
  SELECT * FROM @SearchItms WHERE NOT(
     (OneField IS NOT NULL AND OneField LIKE Item)
  OR (OneDateField IS NOT NULL AND (convert(varchar, OneDateField, 104) LIKE Item) OR (convert(varchar, OneDateField, 114) LIKE Item ) )
  OR (AnotherField IS NOT NULL AND AnotherField LIKE Item)
  OR (LastField IS NOT NULL AND LastField LIKE Item)
  )
)

一件奇怪的事情是,当我删除

--Add last Item
Insert Into @SearchItms (Item) 
Select ('%' + @SearchString + '%')

我没有收到“未从查询返回光标”错误。但是使用搜索字符串,我在 SQL Management Studio 中只得到 10 个结果,我在 Delphi 中得到数据库中的所有项目,就像搜索没有做任何事情一样。

This happens also in a simple test program where I just have a Form, a TSQLConnection, TSQLQuery, TDataSetProvider and a ClientDataSet.

Can someone tell me whats the problem here? Since the query works fine in other environments, I think it should be OK.

Many thanks for any help.

4

2 回答 2

5

As ldsandon mentioned in his post, the problem seems to be, that its not a simple Query, but a complete script. But since non of the other dbExpress units seems to be able to handle this I found a way to make it working.

Just add a SET NOCOUNT ON; to the beginning of the script, and close the script with SET NOCOUNT OFF;

I think this surpresses the 'xx rows effected' message from the inserts and therefore makes it possible to run without errors.

If you know a better way to run the script without errors, let me know.

Thanks.

于 2011-06-27T10:15:32.637 回答
2

This is not a query - this is a script. Usually a Delphi TQuery component can handle a single SQL statement, not multiple ones (you have INSERTs first and then a SELECT). It may be the INSERT that obviously does not return a cursor. You can try to use a TSQLDataset and see if it can handle such a kind of SQL Server "anonymous block", or turn it into a stored procedure and call it from your Delphi program.

于 2011-06-27T09:56:45.993 回答