Using Sql in matlab to get data

3 views (last 30 days)
John Doe
John Doe on 25 Feb 2020
Commented: John Doe on 26 Feb 2020
Hello!
I hope you're doing well.
I want to get specific rows from my data base that have specific IDs.
ID = [8 , 4, 3];
ID = num2str(MissingTrips);
DD = ['SELECT * ' 'FROM Countries WHERE IDNr =',ID]; DD = fetch(conn,DD );
but matlab thinks I'm trying to horzcat when I'm trying to get the data with these IDs, I tried to do mat2str instead of num2str but nothing. How can I get my rows from my Countries table? while usind ID, all at once?
I would appreciat your help on how I can proceed.
Thank you!

Accepted Answer

Guillaume
Guillaume on 25 Feb 2020
Two things about what you've written, a matlab one, and a sql one,
Matlab:
DD = ['SELECT * ' 'FROM Countries WHERE IDNr =']
is the same thing as
DD = ['SELECT * ', 'FROM Countries WHERE IDNr =']
It is a concatenation indeed and I recommend that you always put the , separator so the reader don't have to wonder if you made a mistake. Of course the result of that is:
DD ='SELECT * FROM Countries WHERE IDNr ='
so it's not clear why you didn't write that to start with.
SQL:
WHERE x = y
only allows you to specify one value for y, no more. So your SQL syntax is not correct. To select among a list of values, you use
WHERE x IN (val1, val2, val3, ..)
One way you could compose your statement:
ID = [8 , 4, 3];
IDstring = strjoin(compose('%d', ID), ',');
SQL = sprintf('SELECT * FROM Countries WHERE IDNr IN (%s)', IDstring);

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!