我有2个表,第一个表的字段名称具有以下结构。
CREATE TABLE [dbo].[FieldNames](
[SiteId] [int] NULL,
[Column_1] [nvarchar](50) NULL,
[Column_2] [nvarchar](50) NULL,
[Column_3] [nvarchar](50) NULL,
[Name] [nvarchar](50) NULL
) ON [PRIMARY]
此表包含以下数据
1 FirstName LastName City Coutry
2 City Coutry Name Gender
我还有另一个表,其中包含具有以下结构的列值。
CREATE TABLE [dbo].[FieldValue](
[RowId] [int] NULL,
[SiteId] [int] NULL,
[Column1_Value] [nvarchar](50) NULL,
[Column2_Value] [nvarchar](50) NULL,
[Column3_Value] [nvarchar](50) NULL,
[Name] [nvarchar](50) NULL
) ON [PRIMARY]
此表包含以下数据。
1 1 ABC XYZ Ahmedaad India
2 1 Hello Smith Kodiar India
3 2 Ahmedaad India Happy data
我想要类似siteid = 1
的结果
**FirstName LastName City Coutry**
ABC XYZ Ahmedaad India
Hello Smith Kodiar India
答案 0 :(得分:1)
您真的需要使用这种设计吗?它可能很灵活,但是编码,开发,调试和维护将是一场噩梦。
declare @siteid int = 1
declare @sql nvarchar(max)
select @sql = 'SELECT '
+ '[Column1_Value] as ' + quotename([Column_1]) + ', '
+ '[Column2_Value] as ' + quotename([Column_2]) + ', '
+ '[Column3_Value] as ' + quotename([Column_3]) + ' ' + char(13)
+ 'FROM [FieldValue] v' + char(13)
+ 'WHERE v.[SiteId] = @siteid'
from [FieldNames] n
where n.SiteId = @siteid
print @sql
exec sp_executesql @sql, N'@siteid int', @siteid
答案 1 :(得分:0)
尝试一下
SELECT [FirstName],
[LastName],
[City],
[Coutry]
FROM [FieldNames] n
INNER JOIN [dbo].[FieldValue] v
ON n.[SiteId]=v.[SiteId]
CROSS APPLY ( VALUES ( v.Column1_Value,
v.Column2_Value,
v.Column3_Value,
v.name)
)
dt ([FirstName],[LastName],[City],[Coutry])
WHERE n.[SiteId]=1
结果
FirstName LastName City Coutry
------------------------------------------
ABC XYZ Ahmedaad India
Hello Smith Kodiar India
答案 2 :(得分:0)
我建议通过另一个SQL查询创建相应的(动态)查询,并在循环中执行这些查询(或根据需要单独执行)。以下查询将为您提供动态语句:
SELECT DISTINCT fv.[SiteId],
'SELECT fv.RowId, ' +
'fv.SiteId, ' +
'fv.Column1_Value AS ' + fn.Column_1 + ', ' +
'fv.Column2_Value AS ' + fn.Column_2 + ', ' +
'fv.Column3_Value AS ' + fn.Column_3 + ', ' +
'fv.Name ' +
'FROM [dbo].[FieldValue] fv ' +
'WHERE fv.SiteId = ' + CAST(fv.[SiteId] AS varchar(10)) AS stmt
FROM [dbo].[FieldValue] fv
JOIN [dbo].[FieldNames] fn ON fv.SiteId = fn.SiteId