declare @sql nvarchar(300) DECLARE @intMinId INT,@intMaxId INT,@intClubID INT,@lngUpdateAmount BIGINT,@filename varchar(50) --获取表的列名 SELECT RowID=IDENTITY(INT,1,1),filename INTO #templist FROM (select cl.name as filename from sys.tables AS tb,sys.columns cl where tb.object_id = cl.object_id and tb.name='book') AS A SELECT @intMinId =MIN(RowID),@intMaxId=MAX(RowID) FROM #templist --这里必须设置sql为空字符串,不然设置没数据 set @sql='' WHILE @intMinId<=@intMaxId BEGIN SELECT @filename = filename FROM #templist WHERE RowID=@intMinId if(@intMinId=@intMaxId) begin set @sql = @sql + ' select ' + '''' + @filename + '''' + 'as FileName,' + @filename + ' as value from book where BID=' + '''B001''' end else begin set @sql = @sql+' select '+''''+@filename + '''' + 'as FileName,' + @filename + ' as value from book where BID=' + '''B001''' + ' union all '; end SET @intMinId=@intMinId+1 END print @sql EXEC sp_executesql @sql drop table #templist
找了好久,没找到,自己弄了一个,大家有什么更好的写法,欢迎指教