我有一个包含列的表
a,b,c,d,e,f,g,...,z
是否可以编写一个简单的查询,除了a
之外的所有列都可以不用手动指定所有其他列?
将等同于:
Select b,c,d,e,f,g,h,...z
from TableG
答案 0 :(得分:3)
要回答你的问题,你不能直接这样做,但是我找到了适合你的解决方案。
使用物理表时的SELECT
语句只能SELECT *
返回所有列,而SELECT Column1, Column2, Column3...
返回特定列,没有{ {1}}条件将在SQL的WHERE
语句中排除1列名称。您如何使用临时表
<强>解决方案:强>
从临时表中选择所有数据。
SELECT
我在这里找到了解决方案:SQL exclude a column using SELECT * [except columnA] FROM tableA?
答案 1 :(得分:0)
/************************************************************
Function To Split Strings
************************************************************/
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID('dbo.SplitString') IS NOT NULL
BEGIN
DROP FUNCTION dbo.SplitString
END
GO
create function [dbo].[SplitString]
(
@String varchar(max),
@Delimiter char(1)
)
returns @SplittedValues table
(
str_item varchar(100) primary key
)
as
begin
declare @SplitLength int
while len(@String) > 0
begin
select @SplitLength = (case charindex(@Delimiter,@String) when 0 then
len(@String) else charindex(@Delimiter,@String) -1 end)
insert into @SplittedValues
select substring(@String,1,@SplitLength)
select @String = (case (len(@String) - @SplitLength) when 0 then ''
else right(@String, len(@String) - @SplitLength - 1) end)
end
return
end
GO
/************************************************************
Function To Get columns names excluding some of them
************************************************************/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID('dbo.get_columns') IS NOT NULL
BEGIN
DROP FUNCTION dbo.get_columns
END
GO
CREATE FUNCTION dbo.get_columns
(
@table_name varchar(100),
@excluded_column_names varchar(100),
@delimter char(1)
)
RETURNS varchar(4000)
AS
BEGIN
declare @cols varchar(4000)
select @cols = COALESCE(@cols+',' ,'') + name
from sys.columns
where object_id=object_id(@table_name)
and name not in (select str_item from dbo.SplitString(@excluded_column_names,@delimter))
return @cols
END
GO
/************************************************************
Function To Get columns names excluding some of them
************************************************************/
declare @qry nvarchar(max)
set @qry = ' select ' + dbo.get_columns('TableName','Exclude_col_1,Exclude_col_2,Exclude_col_3',',')
+ ' from TableName'
+ ' where condition'
EXECUTE sp_executesql @qry
GO