tags:

views:

38

answers:

2

INFORMIX-SQL or any other SQL-based DB:

Suppose I have an app where depending on the value of some columns, example:

company.code  char(3) {abc}
company.branch char(2) {01}

Can I construct table name "abc01" for inclusion in SELECT * FROM abc01; ? In other words, a variable table name.. same question applies for column names.

+2  A: 

Only in a language which can manipulate character strings and handle Dynamic SQL. It has to create the statement on the fly.

You can only use placeholders in queries for values, not for the structural elements of the query such as the table name or column name.

Jonathan Leffler
+2  A: 

Only if you use dynamic sql. It's like you build sql code in your app, then use something like execute immediate.

sprintf(cdb_text1, "create table %s (field1 char(3));", usr_db_id);
EXEC SQL execute immediate :cdb_text;

If you use dynamic sql, it's bad because of sql injections.

ksogor
Dynamic SQL used carelessly can certainly lead to [SQL Injection](http://xkcd.org/327) but simply using Dynamic SQL is not automatically a problem. It depends on how careful you are. This particular example does not matter too much; with a CHAR(3) and a CHAR(2) field holding the 'user data', there is not much scope for mischief (Old "Robert'); DROP TABLE Students; --" simply does not fit in 5 characters.
Jonathan Leffler
In this case it's not dangerous. But if I use Dynamic SQL I need/would like know, that this possibility exist, right?
ksogor
If the source of the dynamic values is a user, you need to consider the implications of SQL Injection.If the dynamic aspects of the generated SQL are purely internal business logic to the program, then it's an entirely different matter, and you only need to consider how you deal with unexpected/NULL values appearing in these columns.Having said that, if you find you need to do this, you ought to be casting a very critical eye over your data model. It all sounds very fragile.
RET
@ksogor- The 'abc01' example are validated values held in a control table used for determining which company/branch system the user will work with.
Frank Computer