日期:2014-05-18  浏览次数:20504 次

求循环。。。急
表A
返回
col1 col2
A 部门A
B 部门B
C 部门C


我想要这样的sql
SQL code

--根据表A获得
declare @sql nvarchar(max)
 set sql='select A as  部门A,B as 部门B,C as 部门C from tb'




------解决方案--------------------
SQL code
USE TEMPDB
GO
IF OBJECT_ID('A') IS NOT NULL DROP TABLE A
GO
CREATE TABLE A(
COL1 VARCHAR(10) 
,COL2 VARCHAR(50)
)
INSERT INTO A 
SELECT 'A','部门A' UNION ALL
SELECT 'B','部门B' UNION ALL
SELECT 'C','部门C'
GO
DECLARE @STR VARCHAR(MAX)
SELECT @STR=ISNULL(@STR+',','SELECT ')+''''+COL1+''' AS ['+COL2+']'
FROM A
PRINT (@STR+' FROM TB')
/*
SELECT 'A' AS [部门A],'B' AS [部门B],'C' AS [部门C] FROM TB
*/