求循环。。。急
表A
返回
col1 col2
A 部门A
B 部门B
C 部门C
我想要这样的sql
--根据表A获得declare @sql nvarchar(max) set sql='select A as 部门A,B as 部门B,C as 部门C from tb'
USE TEMPDBGOIF OBJECT_ID('A') IS NOT NULL DROP TABLE AGOCREATE TABLE A(COL1 VARCHAR(10) ,COL2 VARCHAR(50))INSERT INTO A SELECT 'A','部门A' UNION ALLSELECT 'B','部门B' UNION ALLSELECT 'C','部门C'GODECLARE @STR VARCHAR(MAX)SELECT @STR=ISNULL(@STR+',','SELECT ')+''''+COL1+''' AS ['+COL2+']'FROM APRINT (@STR+' FROM TB')/*SELECT 'A' AS [部门A],'B' AS [部门B],'C' AS [部门C] FROM TB*/