您的位置:首页 > 数据库

SQL 对于有N多字段的表,踢出不需要的字段,自动频出剩余字段的SQL语句

2011-08-22 09:46 627 查看
--本例采用northwind数据库的Employees 表,拼出不包括title和firstName 两个字段的SQL 语句

--select * from Employees

declare @index int --默认循环起始值1
declare @ExceptName varchar(200)--要排除的字段名称
declare @indexString int--索引值
declare @InTable varchar(200) --要拼串的表
declare @sql varchar(600) --频出的sql语句
select @ExceptName='title,firstName',@index=1,@sql='select ',@InTable='Employees',@indexString=0 --初始化条件

begin
declare @tempStr nvarchar(800)
declare myCur cursor for ( select name from syscolumns where id=object_id(N''+@InTable+'') )
open myCur
fetch next from myCur into @tempStr
while @@fetch_status = 0
begin

set @tempStr=@tempStr
set @indexString=CHARINDEX(@tempStr, @ExceptName)
if(@indexString=0)
set @sql=@sql+@tempStr+','

fetch next from myCur into @tempStr
end
close myCur
deallocate myCur
end
SELECT @sql=SUBSTRING(@sql,1,(len(@sql)-1))
set @sql=@sql+' from '+@InTable
select @sql

--再判断两个字段 名称相同的问题上,还是有点问题的,再考虑

select EmployeeID,LastName,TitleOfCourtesy,BirthDate,HireDate,Address,City,Region,PostalCode,Country,HomePhone,Extension,Photo,Notes,ReportsTo,PhotoPath from Employees
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: