-1

I have SQL table like this:

create table [Tbl](
   [_Id] int Identity(1, 1),
   [_ProjectId] int,
   [Name] varchar(255),
   [Age] int
   ...
   Primary Key([_Id])
)

I need to select all values but not from the columns which names started by "_" (_Id, _ProjectId). How can I do it?

(For understanding: I have many tables like this with their specific columns. I don't know all the colum names).

4

3 回答 3

2

You list the columns you want in the column list of your query. Don't add the columns that begins with a _.

Update:

You can build the query dynamically in for example a stored procedure where you have table name as a parameter. Use the sys.columns to get the column names and exclude the columns you don't want.

create procedure YourProcedure
  @TableName sysname
as

declare @SQL nvarchar(max)

set @SQL = '
select '+stuff((select ','+quotename(name)
                from sys.columns
                where object_id = object_id(@TableName) and
                      left(name, 1) <> '_'
                for xml path(''), type).value('text()[1]', 'sysname'),1,1,'')+'
from '+quotename(@TableName)

exec sp_executesql @SQL

SQL Fiddle

于 2013-08-04T18:27:45.450 回答
0

You can't use wildcards on column names.

Either select all with

select * from table

or specify which columns you want to select witt their full name

select name, age from table
于 2013-08-04T18:27:58.607 回答
0

List the columns you want separated by commas , instead of *

SELECT Name, Age, Col3, Col4, ColN FROM Tb1
于 2013-08-04T18:29:23.703 回答