NODE.JS MSSQL use SQL NEWID() function as a variable value

Asked

Viewed 69 times

1

Good afternoon!

It has an SQL function (NEWID()) that generates a single key with this format: '6F9619FF-8B86-D011-B42D-00C04FC964FF'

However, when I try to populate a column with the NEWID() value through my NODE server instead of having the key value, the column gets a string 'NEWID'()'

See the example connection below:

function createCotacao() {
let conn = new sql.ConnectionPool(dbConfig);
let req = new sql.Request(conn);

conn.connect(function (err){
    if(err) {
        console.log(err);
        return;
    } 
req.input('chave', sql.VarChar, 'NEWID()');
req.query("INSERT INTO columname (chave) VALUES (@chave)");

If I try to use NEWID() without the quotation marks, it returns an error, and I have tried to use SELECT NEWID() or replace the quotation marks with that string template, but I can’t get the key value... Would anyone know what I’m sinning about? or else tell me some workaround to be able to generate this key as column value through my NODE server.

PS: I am using the MSSQL module to connect to SQL SERVER.

  • 1

    Why don’t you take the input and put NEWID() directly in place of @chave?

  • Putz, Brigadão! here worked!

1 answer

2


NEWID() is an internal function of sql-server, it cannot be used being processed in the code like this: req.input('chave', sql.VarChar, 'NEWID()');

To use it, include it directly in the SQL command:

"INSERT INTO columname (chave) VALUES (NEWID())"

Thus, when executing the query, the entire command will be passed to the database to execute, which will correctly execute the NEWID(), in the same way as any other function/internal control of the seat, such as MAX(), DATEDIFF() or CAST(), for example.

  • Raccoon, I was being stupid... thank you very much! worked here!

  • 1

    quiet, it’s a detail happens :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.