Groovy 使用 sql 服务器数据库一起插入和 select 查询

Groovy insert and select query together using sql server database

我在 groovy 代码中执行 sql 服务器查询时遇到一些问题。我的要求是,我需要从 table ABC.customer 中读取数据并将数据存储到临时 table 测试中。

我的查询是:

DECLARE @throughDate datetime,
        @startDate datetime
DECLARE @test TABLE (
  test_id char(50)
)
SET @throughDate = '5-27-2015'
SET @startDate = DATEADD(YEAR, -1, @throughDate)
INSERT INTO @test
  SELECT
    test_id
  FROM ABC.customer
  WHERE ISNULL(create_date, '1-1-1900') BETWEEN @startDate AND @throughDate
  AND DATEDIFF(MINUTE, ISNULL(create_date, '1-1-1900'), ISNULL(last_login, '1-1-1900')) < 1

我没有连接问题。我可以查询其他 table 和数据。但是 insert 和 select 的组合对我不起作用。

我的 groovy 代码是:

def sql=Sql.newInstance("jdbc:sqlserver://localhost","test","test","com.microsoft.sqlserver.jdbc.SQLServerDriver")


sql.eachRow("""DECLARE  @throughDate DATETIME, @startDate DATETIME
DECLARE @test TABLE(test_id CHAR(50))
SET @throughDate = '5-27-2015' 
SET @startDate = DATEADD(YEAR,-1,@throughDate) 
INSERT INTO @test  SELECT test_id FROM ABC.customer  
WHERE ISNULL(create_date,'1-1-1900') BETWEEN @startDate AND @throughDate  
AND DATEDIFF(minute,ISNULL(create_date,\'1-1-1900\'),ISNULL(last_login,\'1-      
1-1900\')) < 1
select test_id FROM @test
"""){
   println "Value is ${it}"
 }

代码抛出以下异常:

Caught: com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set. com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190) at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:800) at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616) at DataVisualization.SqlServerTest.main(SqlServerTest.groovy:104)

如果有人帮我解决这个问题就好了。

谢谢。

尝试在第一个 SET 之前的查询语句中添加 "SET NOCOUNT ON":

DECLARE  @throughDate DATETIME, @startDate DATETIME
DECLARE @test TABLE(test_id CHAR(50))
SET NOCOUNT ON
SET @throughDate = '5-27-2015' 

sql-服务器将为每个没有 "NOCOUNT" 的 insert/update/select 语句打印一些文本消息,这会打破您的记录集。