sql server - 从一个包含列的表中获取值名称存储在另一个表中
我有几张桌子。这些是表的简化版本:
UsersTable:
UserId FirstName LastName MiddleInit Suffix Age Position
1 John Graham P. Jr. 35 Analyst II
2 Bill Allen T. III 45 Programmer I
3 Jenny Smith K. 25 Systems Engineer
4 Gina Todd J. 55 Analyst II
TableTypes:
TableTypeId TableType
1 Names
2 Positions
3 Age
TableTypeId 是 TableType 中的主键,是 TableField 中的外键。
TableFields:
FieldId TableTypeId FieldName Description
1 1 FirstName descr1
2 1 LastName descr2
3 1 MiddleInit descr3
4 1 Suffix descr4
FieldId 是 TableFields 中的主键,是 ModifiedUsersTable 中的外键。
我需要用 UsersTable 中的值填充 ModifiedUsersTable,因此它看起来像这样:
ModifiedUsersTable:
Id UserId FieldId Value
1 1 1 John
2 1 2 Graham
3 1 3 P.
4 1 4 Jr.
5 2 1 Bill
等等。
我只需要从 UsersTable 中获取 TableFields 表中 FieldName 列中列出的那些列。我事先不知道 TableFields 中的行数(fieldNames)或名称。 我想我应该尝试使用 PIVOT。我可以获得以逗号分隔的列名称字符串,然后动态地将它们转换为列。
但它似乎没有给我我需要的东西。如何填写 ModifiedUsersTable? 有什么建议吗? 谢谢!
I have several tables. These are somewhat simplified versions of the tables:
UsersTable:
UserId FirstName LastName MiddleInit Suffix Age Position
1 John Graham P. Jr. 35 Analyst II
2 Bill Allen T. III 45 Programmer I
3 Jenny Smith K. 25 Systems Engineer
4 Gina Todd J. 55 Analyst II
TableTypes:
TableTypeId TableType
1 Names
2 Positions
3 Age
TableTypeId is primary key in TableTypes and foreign key in TableFields.
TableFields:
FieldId TableTypeId FieldName Description
1 1 FirstName descr1
2 1 LastName descr2
3 1 MiddleInit descr3
4 1 Suffix descr4
FieldId is primary key in TableFields and foreign key in ModifiedUsersTable.
I need to fill ModifiedUsersTable with values from UsersTable so it looks like this:
ModifiedUsersTable:
Id UserId FieldId Value
1 1 1 John
2 1 2 Graham
3 1 3 P.
4 1 4 Jr.
5 2 1 Bill
etc.
I need to get only those columns from UsersTable that are listed in FieldName column in the TableFields table. I don't know the number of rows (fieldNames) or the names in advance in the TableFields.
I thought I should try to use PIVOT. I can get a comma separated string of the column names and then dynamically convert them into columns.
But it doesn't seem to give me what I need. How do I fill ModifiedUsersTable?
Any suggestions?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数据的 DDL
用于填充 ModifiedUsersTable 的脚本
DDL for your data
The script to populate ModifiedUsersTable