Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2011
    Posts
    2

    Unanswered: select query to retrieve value of primary key

    Hi folks,

    I am struggling to retrieve the value of primary for a table. We are using MS SQL Server 2005. The database was designed years back by somebody else (he did n't follow the normalization rules at all). He used Key (which is a keyword in sql server) as the column name for primary key of a table. So I cannot use query like this : "select key from table_name hwere column2 = ? "

    Could anyone help to write a query to get the value of the primary key for a specific row something like this : select primary_key from tbale_name where column2 = ?

    I appreciate your help...

    Thanks,
    SQL Admin

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    column names which contain special characters, or which are reserved words, need to be properly escaped

    in sql server, that's done with square brackets

    try
    Code:
    SELECT [key]
      FROM ...
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Jul 2011
    Posts
    2
    Thank you r937 for the response...

    I tried it before....It was working fine from SQL management studio...but, this query is givng correct value when running from java code....

    I am using simple code like this:

    String query = "select [Key] as realKey from table_name where column2 = ?";
    PreparedStatement stmt = conn.prepareStatement(query);
    stmt.setString(1, "abc");
    ResultSet rs = stmt.executeQuery();

    int keyValue = rs.getInt("realKey");

    It's giving some different value...something like index value etc...

    Thanks in advance...
    Last edited by sqlforum; 07-27-11 at 15:40.

  4. #4
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    if the query works in management studio, and not in java, then the problem is your java code, right?

    sorry, i don't do java
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •