Groovy JDBC应用程序中的SQL列名?

时间:2016-08-25 14:30:37

标签: sql-server jdbc groovy

我们在Groovy程序中使用JDBC访问SQL Server数据库。

我们执行一个查询,并尝试使用如下代码确定输出的列名:

foreach (var words in wordsList) 
{ 
  if (words.StartsWith(defaultName) && !words.StartsWith(dialName)) 
  { 
    messages.Add(wordsList[i]); 
  }   
} 

问题是,对于某些查询,getColumnName()函数返回null。例如,像这样的查询:result = sql.rows(query) { meta -> colNames = (1..meta.columnCount).collect { meta.getColumnName(it) } colTypes = (1..meta.columnCount).collect { meta.getColumnTypeName(it) } colNull = (1..meta.columnCount).collect { meta.isNullable(it) } colAuto = (1..meta.columnCount).collect { meta.isAutoIncrement(it) } } 始终为第二列返回null。

我们检查了" getColumnLabel()"它似乎给了我们与" getColumnName()"相同的价值。

如果没有制定我们自己的方案,当getColumnName()返回null时,是否有推荐的方法来生成列名?

这是Ubuntu 15.04,Java 1.8.0_45,Groovy 1.8.6,SQLJDBC42和SQL Server 2014.

2 个答案:

答案 0 :(得分:0)

您可以将以下查询放在带有参数(schema,objName)的可编程对象中,以列出表或视图的列。

--get the columns of a table
select c.name
from sys.columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = 'Person' and t.schema_id = schema_id('Person');

--get the columns of a view
select c.name
from sys.columns c
inner join sys.views t on c.object_id = t.object_id
where t.name = 'vEmployee' and t.schema_id = schema_id('dbo');

答案 1 :(得分:0)

在您的查询中,您的第二列没有名称。您需要为其指定别名,如下所示:

select name, type_name(user_type_id) AS whatever, max_length from sys.parameters where object_id = object_id('some procedure name')

然后,第二列的名称将显示为whatever

相关问题