--本例采用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