Search code examples
javasqlsql-serverjdbcscalar

Declare an SQL variable in Java


I have connected Java to SSMS and can call data from the server no problems using something like this:

String cell = "SELECT [Close] FROM ExcelData WHERE id_num = 3";
Statement st4 = con.createStatement();
ResultSet rs4 = st4.executeQuery(cell);

while (rs4.next())
{
    Float close = rs4.getFloat("close");
    System.out.format("%s\n", close);
}

When I replace the "SELECT [Close] FROM ExcelData WHERE id_num = 3" to "SELECT @SMA" I get the much questioned "Must declare the scalar variable @SMA.

I do not know how to do that.


Solution

  • Answering my own question to help others who may need to know this... It cannot be done. The work around is to create a table in SQL and insert the variable into the table.

    DROP TABLE IF EXISTS SMA
    CREATE TABLE SMA  (
    SMA_Price DECIMAL (6,5),
    )
    INSERT INTO SMA VALUES (@SMA);
    
    SELECT * FROM SMA;
    

    You can then call "SELECT * FROM SMA" from Java.