创建存储过程以从其他(多个)表列填充表

时间:2013-05-31 14:46:47

标签: sql-server tsql stored-procedures transactions

我需要创建一个存储过程事务,它将从两个表中提取数据并创建一个随机整数来填充第三个表(dbo.patient_address)。

我想要以下内容,但我很难理解如何将其编写为存储过程。

dbo.address AddressID = dbo.patient_address AddressID, dbo.patient PatientID = dbo.patient_address PatientID, RAND是1-3之间的整数(参见dbo.addresstype)= dbo.patient_address AddressTypeID

以下是所有这些表的create语句。

ADDRESS TABLE - 30000行(完整数据集)

CREATE TABLE [dbo].[ADDRESS](
    [AddressID] [int] NOT NULL,
    [StreetAddress] [varchar](50) NULL,
    [City] [varchar](50) NULL,
    [State] [varchar](50) NULL,
    [PostalCode] [varchar](50) NULL,
 CONSTRAINT [ADDRESS_PK] PRIMARY KEY CLUSTERED 
(
    [AddressID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

PATIENT TABLE - 30000行(完整数据集)

CREATE TABLE [dbo].[PATIENT](
    [PatientID] [int] NOT NULL,
    [PatientFName] [varchar](50) NOT NULL,
    [PatientLName] [varchar](50) NOT NULL,
    [GenderID] [int] NOT NULL,
    [DateOfBirth] [date] NOT NULL,
 CONSTRAINT [PATIENT_PK] PRIMARY KEY CLUSTERED 
(
    [PatientID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ADDRESS TYPE - 3种选择(主页,结算,工作) - 1到3之间的整数

CREATE TABLE [dbo].[ADDRESS_TYPE](
    [AddressTypeID] [int] NOT NULL,
    [AddressTypeName] [varchar](10) NOT NULL,
    [AddressTypeDescr] [varchar](10) NULL,
 CONSTRAINT [ADDRESS_TYPE_PK] PRIMARY KEY CLUSTERED 
(
    [AddressTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO [dbo].[ADDRESS_TYPE]
([AddressTypeID],[AddressTypeName],[AddressTypeDescr])
Values ('1','Home','Home'), ('2','Bill','Billing'), ('3','Work','Work')

这是我想使用存储过程事务从所有上述表中填充的最终表。

CREATE TABLE [dbo].[PATIENT_ADDRESS](
    [PatientID] [int] NOT NULL,
    [AddressID] [int] NOT NULL,
    [AddressTypeID] [int] NULL,
 CONSTRAINT [PATIENT_ADDRESS_PK] PRIMARY KEY CLUSTERED 
(
    [PatientID] ASC,
    [AddressID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

1 个答案:

答案 0 :(得分:0)

试试这个:

INSERT INTO PATIENT_ADDRESS
SELECT PatientID, AddressID, 
    CONVERT(INT,(ABS(CHECKSUM(NEWID())/2148000000.))*3)+1 AS AddressTypeID
FROM (
    SELECT PatientID, ROW_NUMBER() OVER (ORDER BY PatientID) AS RowNum 
    FROM dbo.PATIENT
) x
INNER JOIN (
    SELECT AddressID, ROW_NUMBER() OVER (ORDER BY AddressID) AS RowNum 
    FROM dbo.ADDRESS
) y ON x.RowNum = y.RowNum