'附近的语法不正确sys.objects'

时间:2016-10-01 19:46:33

标签: java sql sql-server database jdbc

我收到错误消息

  

com.microsoft.sqlserver.jdbc.SQLServerException:' sys'附近的语法不正确。

这通常意味着我输入的SQL查询错误或者我缺少语法。我非常确定我使用的SQL查询是正确的:

  public static Vector<Vector<String>> getKeys() throws SQLException {
    Vector<Vector<String>> vs = new Vector<Vector<String>>();
    Connection con = Dal2.getConnection();
    Statement stm = con.createStatement();
    ResultSet rSet;
    String sqlString = "SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,"
            +"SCHEMA_NAME(schema_id) AS SchemaName,"
            + "OBJECT_NAME(parent_object_id) AS TableName,"
            +"type_desc AS ConstraintType"
            +"FROM sys.objects"
            +"WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')";

    try{
        rSet = stm.executeQuery(sqlString);
        while(rSet.next()){
            Vector<String> v = new Vector<String>();
            for(int i=1; i <= v.size(); i++){
                System.out.println(rSet.getString(i) + "\n");
         //                 v.add(rSet.getString(i));
            }
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    return vs;

正如您所看到的,我想在使用该方法时在Java控制台上打印出SQL结果集。但我不断收到语法错误。我在SQL Server中尝试过SQL查询,它运行正常:

SELECT  OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
        SCHEMA_NAME(schema_id) AS SchemaName, 
        OBJECT_NAME(parent_object_id) AS TableName,
        type_desc AS ConstraintType
FROM sys.objects 
WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')

2 个答案:

答案 0 :(得分:1)

连接字符串如下所示:

SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,SCHEMA_NAME(schema_id) AS SchemaName,OBJECT_NAME(parent_object_id) AS TableName,type_desc AS ConstraintTypeFROM sys.objectsWHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')

请注意ConstraintTypeFROM sys.objectsWHERE部分。它缺少空格,导致SQL语法错误。

通常,最好在每个连接到最终查询的SQL行的末尾添加一个空格。这样你就不必在换行时考虑空格了:

String sqlString = "SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint, " // <<== Space
        +"SCHEMA_NAME(schema_id) AS SchemaName, "                        // <<== Space
        + "OBJECT_NAME(parent_object_id) AS TableName, "                 // <<== Space
        +"type_desc AS ConstraintType "                                  // <<== Space
        +"FROM sys.objects "                                             // <<== Space
        +"WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')";

答案 1 :(得分:0)

您的sqlString在您的查询的两个地方缺少空格字符

String sqlString = "SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,"
        + "SCHEMA_NAME(schema_id) AS SchemaName," 
        + "OBJECT_NAME(parent_object_id) AS TableName,"
        + "type_desc AS ConstraintType " // <-- here
        + "FROM sys.objects " // <-- here
        + "WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')";

tl; dr 目前您的查询评估为(部分)ConstraintTypeFROM sys.objectsWHERE