sql >> Base de Datos >  >> RDS >> Sqlserver

¿Hay alguna manera de hacer otra consulta dentro de la consulta de inserción?

Configuración:

USE TempDB;
GO

CREATE TABLE dbo.Leads
(
    LeadID VARCHAR(64),
    CreateUser VARCHAR(32),
    CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FirstName VARCHAR(32),
    AccountID INT
);

CREATE TABLE dbo.Accounts
(
    AccountID INT IDENTITY(1,1),
    name VARCHAR(32) /* , ... other columns ... */
);

CREATE TABLE dbo.Temp(name VARCHAR(32));

INSERT dbo.Temp SELECT 'foo'
UNION SELECT 'bar';

Consulta:

INSERT dbo.Accounts
(
    name
)
OUTPUT
    'Q' + cast(floor(999997 * RAND(convert(varbinary, newid()))) as varchar(20)),
    'U6UJ9000S',
    CURRENT_TIMESTAMP,
    inserted.name,
    inserted.AccountID
INTO dbo.Leads
SELECT name
FROM dbo.Temp;

Comprobar:

SELECT * FROM dbo.Accounts;
SELECT * FROM dbo.Leads;

Limpieza:

USE tempdb;
GO
DROP TABLE dbo.Temp, dbo.Accounts, dbo.Leads;