Zapnologica
Zapnologica

Reputation: 22556

Add a column to an select SQL query

I have a sql query that selects certain attributes from a table, it looks as follows:

SELECT [pk], [TagGenNo], [Enabled] FROM [TagNumbers]

Now I want my sql query to return the data with an additional column called selected which is defaulted to false and is of type bit / boolean.

So it will return a result as follows:

pk    TagGenNo    Enabled    Selected
100   03          1          0
101   023         0          0

Upvotes: 0

Views: 100

Answers (1)

lc.
lc.

Reputation: 116498

I am assuming you just want a column full of zeroes in your results. If so, just select a constant:

SELECT [pk], [TagGenNo], [Enabled], CAST(0 AS bit) AS [Selected] FROM [TagNumbers]

As a side note, while this does have its applications (e.g. inserting data into another table which does not have a default value) you may want to think twice about your application's architecture. If the value of this column is always a constant and never persisted back to the database, there is really no benefit to generating this value at the database side and having to send a whole bunch of zeroes back through the wire. (Not to mention it strongly couples the persistence layer with the controller or presentation layer).

Following your comment, I would suggest to keep a boolean property Selected of each object in the object itself, with a default of false at construction time. This way your database doesn't have to know anything about "object selection"

Upvotes: 4

Related Questions