Obtener SQL Insert para el trabajo cuando se suministra PK o NO
-
28-09-2019 - |
Pregunta
Tengo el siguiente procedimiento almacenado:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
@ServerEnvironmentName varchar(50),
@ServerEnvironmentDescription varchar(1000),
@UserCreatedId uniqueidentifier,
@ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
VALUES
(
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
-- If @ServerEnvironmentId was not supplied.
IF (@ServerEnvironmentId IS NULL)
BEGIN
-- Get the ServerEnvironmentId.
SELECT @ServerEnvironmentId = ServerEnvironmentId
FROM @APPL_ServerEnvironment
END
La columna ServerEnvironmentId es una clave principal con un conjunto predeterminado en él, que es (newsequentialid ()).
Necesito este procedimiento almacenado para el trabajo durante 2 escenarios:
- valor suministrado por ServerEnvironmentId -. WORKS
- El valor no suministrado para ServerEnvironmentId - no funciona - CAN NOT INSERT valor nulo. Pensé mediante el establecimiento de un defecto en esta columna éste estaría bien.
Alguien por favor ayuda a enmendar este procedimiento para que pueda funcionar para ambos escenarios. necesidades solución para tener cambios mínimos como todo sp Actualmente está siguiendo esta tendencia.
Otros consejos
Los valores por defecto se aplican solamente en inserciones si la columna no está incluido en la lista de inserción. Lo recomendaría el siguiente cambio no del todo trivial (he comentado las líneas a ser eliminados):
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
@ServerEnvironmentName varchar(50),
@ServerEnvironmentDescription varchar(1000),
@UserCreatedId uniqueidentifier,
@ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
---- Stores the ServerEnvironmentId.
--DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF @ServerEnvironmentName is null
SET @ServerEnvironmentName = newid()
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
--OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
VALUES
(
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
---- If @ServerEnvironmentId was not supplied.
--IF (@ServerEnvironmentId IS NULL)
--BEGIN
-- -- Get the ServerEnvironmentId.
-- SELECT @ServerEnvironmentId = ServerEnvironmentId
-- FROM @APPL_ServerEnvironment
--END
La restricción predeterminada no será utilizado por este procedimiento, pero se puede dejar en su lugar si hay otros lugares donde las filas se pueden añadir a la mesa.
(Mi primera respuesta fue larga y por lo que éste, por lo que estoy publicar una segunda respuesta.)
Me faltó que estaba utilizando NEWSEQUENTIALID. Una vez más, si no se especifica una columna dentro de la instrucción de inserción, no se utilizarán los valores predeterminados asignados a esa columna [ a menos que utilice la palabra clave DEFAULT en la instrucción INSERT, pero que sigue siendo todo o nada - no se puede decir "si @var es nulo y de esta forma"] . Creo que usted está atascado con ramificación simple y el código semi-redundante, a lo largo de las líneas de:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
@ServerEnvironmentName varchar(50),
@ServerEnvironmentDescription varchar(1000),
@UserCreatedId uniqueidentifier,
@ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF @ServerEnvironmentId is null
BEGIN
-- ServerEnvironmentId not provided by user, generate during the insert
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
VALUES
(
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
-- Get the new ServerEnvironmentId
SELECT @ServerEnvironmentId = ServerEnvironmentId
FROM @APPL_ServerEnvironment
END
ELSE
BEGIN
-- ServerEnvironmentId is provided by user
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId,
ServerEnvironmentId
)
OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
VALUES
(
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId,
@ServerEnvironmentId
)
END
(¿Por qué bloquear la tabla entera durante la inserción?)