TSQL - 如何从一个结果集中的多个表连接 1..*?
位置表记录有两个地址 ID - 引用地址表的邮寄地址 ID 和商业地址 ID。
因此,地址表将包含给定地址 ID 的最多两条记录。
给定一个位置 ID,我需要一个存储过程来返回一个结果集中的所有 tbl_Location 字段和所有 tbl_Address 字段:
LocationID INT,
ClientID INT,
LocationName NVARCHAR(50),
LocationDescription NVARCHAR(50),
MailingAddressID INT,
BillingAddressID INT,
MAddress1 NVARCHAR(255),
MAddress2 NVARCHAR(255),
MCity NVARCHAR(50),
MState NVARCHAR(50),
MZip NVARCHAR(10),
MCountry CHAR(3),
BAddress1 NVARCHAR(255),
BAddress2 NVARCHAR(255),
BCity NVARCHAR(50),
BState NVARCHAR(50),
BZip NVARCHAR(10),
BCountry CHAR(3)
我首先创建一个包含所需字段的临时表,但对如何完成此操作有点困惑。
我可以对每个必需的地址字段进行子选择,但看起来有点混乱。
我已经有了一个表值函数,它接受地址 ID,并返回该 ID 的所有字段,但不确定如何将其集成到我所需的结果中。
顺便说一句,看起来需要 3 个选择来创建此表 - 1:位置,2:邮寄地址,3:帐单地址。
我想做的只是创建一个视图并使用它。
任何帮助都会有所帮助。
谢谢。
A location table record has two address id's - mailing and business addressID that refer to an address table.
Thus, the address table will contain up to two records for a given addressID.
Given a location ID, I need an sproc to return all tbl_Location fields, and all tbl_Address fields in one resultset:
LocationID INT,
ClientID INT,
LocationName NVARCHAR(50),
LocationDescription NVARCHAR(50),
MailingAddressID INT,
BillingAddressID INT,
MAddress1 NVARCHAR(255),
MAddress2 NVARCHAR(255),
MCity NVARCHAR(50),
MState NVARCHAR(50),
MZip NVARCHAR(10),
MCountry CHAR(3),
BAddress1 NVARCHAR(255),
BAddress2 NVARCHAR(255),
BCity NVARCHAR(50),
BState NVARCHAR(50),
BZip NVARCHAR(10),
BCountry CHAR(3)
I've started by creating a temp table with the required fields, but am a bit stuck on how to accomplish this.
I could do sub-selects for each of the required address fields, but seems a bit messy.
I've already got a table-valued-function that accepts an address ID, and returns all fields for that ID, but not sure how to integrate it into my required result.
Off hand, it looks like 3 selects to create this table - 1: Location, 2: Mailing address, 3: Billing address.
What I'd like to do is just create a view and use that.
Any assistance would be helpful.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类似以下内容的内容会起作用:
我没有输入所有字段,但您明白了。
请注意,如果任一地址 ID 可能为空,则您可以改用左连接。
something along the lines of the following would work:
I didn't put in all of the fields, but you get the idea.
Note that if either of the address ids could be null, the you might use a left join instead.
如果我正确理解你的问题,你想要这样的东西:
If I understand your question correctly you want something like: