我有一张表Configs
,其中我有列名
id | Name
-------------
1 | Fruits
2 | Vegetables
3 | Pulses
我有另一张桌子说Details
id |Field1 | Field2| Field3 | Active | Mandatory
-------------------------------------------------
1 |Apple |Potato |Red gram | 1 |0
2 |Mango |Peas |Chick Peas| 0 |0
我需要选择field1,field2,field3作为第一个表的名称 例如
select
id,
Field1 as Fruits,
Field2 as Vegetables,
Field3 as pulses,
Active,
Mandatory
From
Details
我该怎么做?
答案 0 :(得分:3)
declare @sql nvarchar(max)
select @sql = isnull(@sql + ',' ,'')
+ N'Field' + convert(varchar(10), id) + ' as ' + quotename(Name)
from Config
-- Form the dynamic SQL
select @sql = 'SELECT id,'
+ @sql
+ ',Active, Mandatory '
+ 'FROM Details'
-- Print to verify
print @sql
-- Execute it
exec sp_executesql @sql
答案 1 :(得分:2)
或许这样的事情:
IF OBJECT_ID(N'Configs', N'U') IS NULL
CREATE TABLE Configs(ID INT, Name NVARCHAR(25));
ELSE
TRUNCATE TABLE Configs
INSERT INTO Configs VALUES(1, 'Fruits'), (2, 'Vegetables'), (3, 'Pulses');
IF OBJECT_ID(N'Configs', N'U') IS NULL
CREATE TABLE Details(ID INT, Field1 NVARCHAR(25), Field2 NVARCHAR(25), Field3 NVARCHAR(25)
,Active BIT, Mandatory BIT);
ELSE
TRUNCATE TABLE Details
INSERT INTO Details VALUES(1, 'Apples', 'Potato', 'Red Gram', 1, 0)
,(2, 'Mango', 'Peas', 'Chick Peas', 0, 0);
DECLARE @Sql NVARCHAR(MAX);
SELECT @Sql = 'SELECT id,' + CHAR(13)
+ ' [Field1] as ' + QUOTENAME((SELECT Name FROM Configs WHERE ID = 1)) +',' + CHAR(13)
+ ' [Field2] as ' + QUOTENAME((SELECT Name FROM Configs WHERE ID = 2)) +',' + CHAR(13)
+ ' [Field3] as ' + QUOTENAME((SELECT Name FROM Configs WHERE ID = 3)) +',' + CHAR(13)
+ ' Active,' + CHAR(13)
+ ' Mandatory ' + CHAR(13)
+ 'From Details' + CHAR(13);
PRINT @Sql;
EXEC sp_executesql @Sql;
IF OBJECT_ID(N'Configs', N'U') IS NULL
CREATE TABLE Configs(ID INT, Name NVARCHAR(25));
ELSE
TRUNCATE TABLE Configs
INSERT INTO Configs VALUES(1, 'Fruits'), (2, 'Vegetables'), (3, 'Pulses');
IF OBJECT_ID(N'Configs', N'U') IS NULL
CREATE TABLE Details(ID INT, Field1 NVARCHAR(25), Field2 NVARCHAR(25), Field3 NVARCHAR(25)
,Active BIT, Mandatory BIT);
ELSE
TRUNCATE TABLE Details
INSERT INTO Details VALUES(1, 'Apples', 'Potato', 'Red Gram', 1, 0)
,(2, 'Mango', 'Peas', 'Chick Peas', 0, 0);
DECLARE @Sql NVARCHAR(MAX) = 'SELECT' + CHAR(13) + CHAR(9) + 'ID' + CHAR(13);
SELECT
@Sql += STUFF((
SELECT
CHAR(9) + ',' + QUOTENAME('Field' + LTRIM(STR(ROW_NUMBER()OVER(ORDER BY ID)))) + ' AS ' + QUOTENAME(Name) + CHAR(13)
FROM
Configs
FOR XML PATH(''), type).value('.', 'nvarchar(max)'), 1, 0, '');
SELECT
@Sql += CHAR(9) +',Active' + CHAR(13)
+ CHAR(9) +',Mandatory ' + CHAR(13)
+ 'From Details' + CHAR(13);
PRINT @Sql;
EXEC sp_executesql @Sql;