我有两张桌子
CUSTOMERS
,其中包含CustomerId, CustomerName
列LICENSES
,其中包含LicenseId, Customer
列第二个表格中的Customer
列是第一个表格中的CustomerId
我想创建一个将值插入表2的存储过程
Insert into Licenses (Customer)
Values(CustomerId)
如何从其他表中获取此数据?
提前感谢您提供任何帮助
答案 0 :(得分:0)
CREATE PROCEDURE uspInsertToTable
@CustomerID INT OUTPUT,
@CustomerName VARCHAR(50),
@LicenseID INT,
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO CUSTOMERS
VALUES (@CustomerName);
SET @CustomerID=SCOPE_IDENTITY();
INSERT INTO LICENSES
VALUES (@LicenseID, @CustomerID)
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
END CATCH;
END;
];
如果CustomerID是身份,我希望它能起作用...... :)
答案 1 :(得分:0)
这对我来说只是一个语法问题 - 我想你想要的是
INSERT INTO Licenses (Customer) SELECT CustomerId FROM customers where ...
答案 2 :(得分:-1)
如果你正在使用SQL Server
而你的PK
使用identity(1,1)
进行自相关,请执行以下操作:
CREATE PROC Register @CustomerName varchar(25)
AS BEGIN
INSERT INTO CUSTOMERS (Customer) VALUES (@CustomerName)
INSERT INTO LICENSES (SELECT MAX(CustomerId) FROM CUSTOMERS)
END
但如果你不想使用identity (1,1)
,请执行以下操作:
CREATE PROC Register @CustomerName varchar(25)
AS BEGIN
DECLARE @idc int = SELECT MAX(CustomerId) FROM CUSTOMERS;
DECLARE @idl int = SELECT MAX(LicenseId) FROM LICENSES ;
INSERT INTO CUSTOMERS (CustomerId, CustomerName) VALUES (@idc,@CustomerName)
INSERT INTO LICENSES (LicenseId, Customer) VALUES (@idl,@idc)--I guess your field Customer is the foreign key
END