如何在SQL上选择没有2列的所有列

时间:2016-08-27 08:33:27

标签: sql select

我需要选择所有列但没有2列,如下所示

CREATE TABLE product(id int, name varchar(50), inf varchar(50));
CREATE TABLE users(id int,prdct_id int,user1 float,user2 float, ...... , usern float);

select p.id,p.name,p.inf,u.* ???("without id and prdct_id column)???    
from product p join
     users u
     on p.id = u.prdct_id

我希望,你们了解我,如何选择没有id和prdct_id列的所有用户列。我不想写每个用户名来选择。

2 个答案:

答案 0 :(得分:0)

使用以下脚本获得所需的结果..

DECLARE @selectlist NVARCHAR(max)
DECLARE @QueryString NVARCHAR(max)

SELECT @selectlist='p.id,p.name,p.inf,'+stuff((SELECT distinct ',u.' + ISNULL([name],'')
FROM  syscolumns 
WHERE id= OBJECT_ID('users')
AND name not in ('id','prdct_id')  FOR XML PATH('')),1,1,'')

SET @QueryString='SELECT '+@selectlist+' FROM product p 
                    JOIN users u ON p.id = u.prdct_id'

EXEC (@QueryString)

答案 1 :(得分:0)

DECLARE @QueryStr VARCHAR(500),@EXECStr VARCHAR(200)

SELECT @QueryStr = 
(
    STUFF( ( SELECT ',' + name FROM  syscolumns 
    WHERE name NOT IN ('Column_name') AND id= OBJECT_ID('table_name') FOR XML PATH('') ),1,1,'' )
)

SET @EXECStr = 'SELECT '+@QueryStr+' FROM table_name'

EXEC (@EXECStr)