I am trying to implement two insert statements in one SQL Server stored procedure. I did something like this, but the second insert statement does not work. Any ideas? Thanks.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertWrite]
#Die nvarchar(8),
#TSO int,
#TSOStatus nvarchar(50);
as
BEGIN
SET NOCOUNT OFF;
INSERT INTO Table1 (TSO, TSOStatus)
VALUES (#TSO, #TSOStatus)
if ##rowcount > 0
BEGIN
INSERT INTO Table2 (TSO, Die)
VALUES (#TSO, #Die);
COMMIT
END
ELSE
ROLLBACK
END
You don't need that extra commit and rollback since I don't see anywhere you started the transaction. Not sure exactly what you are trying but the below code works just fine
CREATE PROCEDURE [dbo].[InsertWrite]
#Die varchar(8),
#TSO varchar(10),
#TSOStatus varchar(50)
as
BEGIN
SET NOCOUNT OFF;
INSERT INTO Tab1 (TSO, TSOStatus) Values (#TSO,#TSOStatus);
if ##rowcount > 0
INSERT INTO Tab2 (TSO,Die) Values (#TSO, #Die);
END
You can simplify this considerably:
create procedure dbo.InsertWrite
#Die nvarchar(8) ,
#TSO int ,
#TSOStatus nvarchar(50)
as
set nocount on
begin transaction
begin try
insert Table1 ( TSO , TSOStatus ) values ( #TSO , #TSOStatus )
insert Table2 ( TSO , Die ) values ( #TSO , #Die )
commit transaction
end try
begin catch
rollback transaction
throw
end catch
return 0
go
Related
I am trying to insert asp.net grid data to database table [DBO].[tbl_family_member]. I've created a type typ_fam_mem for this. But the problem is the column family_member_id value is generated from another table [DBO].[TBL_FAMILY_HEAD]. Please look at the procedure.
How can I insert data to the table from a datatable and procedure variables?
CREATE TABLE [DBO].[tbl_family_member]
(
family_member_id bigint identity(1,1) not null,
family_head_id bigint NOT NULL,
mem_name nvarchar(200) not null,
mem_gender tinyint not null,
mem_occupation nvarchar(50),
mem_maritial_status tinyint,
STATUS INT NOT NULL DEFAULT '1',
CONSTRAINT pk_family_member PRIMARY KEY (family_member_id)
)
create type typ_fam_mem as table
(
mem_name nvarchar(200) not null,
mem_gender tinyint not null,
mem_occupation nvarchar(50),
mem_maritial_status tinyint
)
Stored procedure
CREATE PROCEDURE [dbo].[P_SET_PROFILE_REGISTRATION]
(
--- FOR FAMILY HEAD TABLE
#P_NAME NVARCHAR(200),
#P_GENDER TINYINT,
---- FOR FAMILY MEMBER
#P_FAMILY_DT DBO.typ_fam_mem READONLY,
#V_OUT TINYINT OUTPUT
)
AS
DECLARE #FAMILY_HEAD_ID BIGINT;
BEGIN
SET NOCOUNT ON;
BEGIN TRY
INSERT INTO [DBO].[TBL_FAMILY_HEAD] ([NAME], [GENDER])
VALUES (#P_NAME, #P_GENDER)
SET #FAMILY_HEAD_ID = SCOPE_IDENTITY();
IF ##ROWCOUNT > 0
BEGIN
--- block for inserting data into [DBO].[tbl_family_member]
END
END TRY
BEGIN CATCH
END CATCH
END
#P_FAMILY_DT is a table type, you can query the table type like a normal table.
Your insert should look like
INSERT INTO [DBO].[tbl_family_member]
(family_head_id,
mem_name,
mem_gender,
mem_occupationm,
mem_maritial_status)
SELECT #FAMILY_HEAD_ID,
mem_name,
mem_gender,
mem_occupation,
mem_maritial_status
FROM #P_FAMILY_DT
You can use INSERT...SELECT, specifying the variable with the generated value. The example below also adds a transaction management (appropriate for multi-table inserts unless client app manages the transaction) and error handling.
CREATE PROCEDURE [dbo].[P_SET_PROFILE_REGISTRATION]
--- FOR FAMILY HEAD TABLE
#P_NAME NVARCHAR(200),
#P_GENDER TINYINT,
---- FOR FAMILY MEMBER
#P_FAMILY_DT DBO.typ_fam_mem READONLY,
#V_OUT TINYINT OUTPUT
AS
DECLARE #FAMILY_HEAD_ID BIGINT;
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRAN;
INSERT INTO [DBO].[TBL_FAMILY_HEAD] ([NAME], [GENDER])
VALUES (#P_NAME, #P_GENDER)
SET #FAMILY_HEAD_ID = SCOPE_IDENTITY();
INSERT INTO dbo.tbl_family_member(
mem_name
, mem_gender
, mem_occupation
, mem_maritial_status
, family_head_id
)
SELECT
mem_name
, mem_gender
, mem_occupation
, mem_maritial_status
, #FAMILY_HEAD_ID
FROM #P_FAMILY_DT;
COMMIT;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
GO
We have a DACPAC (sqlproj) solution which has some tables and a post-deployment script which runs some DML queries.
If the DML query fails (I'm raising an error with severity=20), I would like to rollback all changes - including the DDL changes done by the dacpac and the post-deployment file changes. This is especially useful when I would be upgrading an existing target database.
I'm striving for an atomic DB upgrade when the DACPAC is published - all DDL changes mentioned in the DACPAC solution should be published only when everything in the post deployment script is successful.
Since DACPAC DDL changes are committed before it invokes post-deployment script, I thought generating all the DAC changes as a single script file using DacServices.GenerateDeployScript will help. Doesnt look so straight forward.
Has anyone tried something like this (and failed/passed)?
I'm facing many challenges like...
Create/alter Database shouldnt be in a transaction.
Rollback not happening at all.
[Edit 10Nov]: Pasting the deploy script generated by the dacpac here, so that I can explain my issue better (hopefully)
/*
Deployment script for 9Nov
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
GO
:setvar INSTALL_DIR "D:\EDW_9Nov\"
:setvar DatabaseName "9Nov"
:setvar DefaultFilePrefix "9Nov"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\"
GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
SET NOEXEC ON;
END
GO
USE [master];
GO
IF (DB_ID(N'$(DatabaseName)') IS NOT NULL)
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [$(DatabaseName)];
END
GO
PRINT N'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [$(DatabaseName)], FILENAME = N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
LOG ON (NAME = [$(DatabaseName)_log], FILENAME = N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE SQL_Latin1_General_CP1_CI_AS
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET ANSI_NULLS ON,
ANSI_PADDING ON,
ANSI_WARNINGS ON,
ARITHABORT ON,
CONCAT_NULL_YIELDS_NULL ON,
NUMERIC_ROUNDABORT OFF,
QUOTED_IDENTIFIER ON,
ANSI_NULL_DEFAULT ON,
CURSOR_DEFAULT LOCAL,
RECOVERY SIMPLE,
CURSOR_CLOSE_ON_COMMIT OFF,
AUTO_CREATE_STATISTICS ON,
AUTO_SHRINK OFF,
AUTO_UPDATE_STATISTICS ON,
RECURSIVE_TRIGGERS OFF
WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [$(DatabaseName)]
SET AUTO_CLOSE OFF
WITH ROLLBACK IMMEDIATE;
END
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET ALLOW_SNAPSHOT_ISOLATION OFF;
END
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET READ_COMMITTED_SNAPSHOT OFF
WITH ROLLBACK IMMEDIATE;
END
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET AUTO_UPDATE_STATISTICS_ASYNC OFF,
PAGE_VERIFY NONE,
DATE_CORRELATION_OPTIMIZATION OFF,
DISABLE_BROKER,
PARAMETERIZATION SIMPLE,
SUPPLEMENTAL_LOGGING OFF
WITH ROLLBACK IMMEDIATE;
END
GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
BEGIN
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
SET TRUSTWORTHY OFF,
DB_CHAINING OFF
WITH ROLLBACK IMMEDIATE';
END
END
ELSE
BEGIN
PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
END
GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
BEGIN
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
SET HONOR_BROKER_PRIORITY OFF
WITH ROLLBACK IMMEDIATE';
END
END
ELSE
BEGIN
PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
END
GO
ALTER DATABASE [$(DatabaseName)]
SET TARGET_RECOVERY_TIME = 0 SECONDS
WITH ROLLBACK IMMEDIATE;
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF),
CONTAINMENT = NONE
WITH ROLLBACK IMMEDIATE;
END
GO
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
ALTER DATABASE [$(DatabaseName)]
SET AUTO_CREATE_STATISTICS ON(INCREMENTAL = OFF),
MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT = OFF,
DELAYED_DURABILITY = DISABLED
WITH ROLLBACK IMMEDIATE;
END
GO
USE [$(DatabaseName)];
GO
IF fulltextserviceproperty(N'IsFulltextInstalled') = 1
EXECUTE sp_fulltext_database 'enable';
GO
PRINT N'Creating [EDW_INTERNAL]...';
GO
CREATE SCHEMA [EDW_INTERNAL]
AUTHORIZATION [dbo];
GO
PRINT N'Creating [EDW_INTERNAL].[DB_VERSIONS]...';
GO
CREATE TABLE [EDW_INTERNAL].[DB_VERSIONS] (
[ID] BIGINT IDENTITY (1, 1) NOT NULL,
[MODULE] VARCHAR (30) NOT NULL,
[FROM_VERSION] VARCHAR (20) NOT NULL,
[TO_VERSION] VARCHAR (20) NOT NULL,
[UPGRADE_DML_APPLIED_YN] VARCHAR (1) NOT NULL,
CONSTRAINT [PK_DB_VERSIONS] PRIMARY KEY CLUSTERED ([MODULE] ASC, [FROM_VERSION] ASC, [TO_VERSION] ASC)
);
GO
PRINT N'Creating [EDW_INTERNAL].[DML_UPGR_SCRIPT_MASTER]...';
GO
CREATE TABLE [EDW_INTERNAL].[DML_UPGR_SCRIPT_MASTER] (
[MODULE] VARCHAR (30) NOT NULL,
[FROM_VERSION] VARCHAR (20) NOT NULL,
[TO_VERSION] VARCHAR (20) NOT NULL,
[APPLY_ORDER] INT NOT NULL,
[UPGR_SCRIPT_FILEPATH] VARCHAR (1024) NOT NULL,
CONSTRAINT [PK_DML_UPGR_SCRIPT_MASTER] PRIMARY KEY CLUSTERED ([APPLY_ORDER] ASC, [TO_VERSION] ASC, [FROM_VERSION] ASC, [MODULE] ASC)
);
GO
PRINT N'Creating unnamed constraint on [EDW_INTERNAL].[DB_VERSIONS]...';
GO
ALTER TABLE [EDW_INTERNAL].[DB_VERSIONS]
ADD DEFAULT 'N' FOR [UPGRADE_DML_APPLIED_YN];
GO
PRINT N'Creating [EDW_INTERNAL].[UPGRADE_DML]...';
GO
CREATE PROCEDURE EDW_INTERNAL.UPGRADE_DML
#Module VARCHAR(30)
AS
BEGIN
DECLARE #Failure bit = 1;
IF #Failure = 1
BEGIN
RAISERROR
(N'One or more database upgrade query statements have failed. Please check the DML Upgrade Log table for details.',
20, -- Severity.
1 -- State
) WITH LOG;
END
END
GO
/*
Post-Deployment Script Template
--------------------------------------------------------------------------------------
This file contains SQL statements that will be appended to the build script.
Use SQLCMD syntax to include a file in the post-deployment script.
Example: :r .\myfile.sql
Use SQLCMD syntax to reference a variable in the post-deployment script.
Example: :setvar TableName MyTable
SELECT * FROM [$(TableName)]
--------------------------------------------------------------------------------------
*/
-- Reference to load the Version Upgrade tables with rows
--:r VersionUpgradeRowsPopulate.sql
-- execute
EXEC [EDW_INTERNAL].[UPGRADE_DML] #MODULE = 'Test_Common'
GO
GO
DECLARE #VarDecimalSupported AS BIT;
SELECT #VarDecimalSupported = 0;
IF ((ServerProperty(N'EngineEdition') = 3)
AND (((##microsoftversion / power(2, 24) = 9)
AND (##microsoftversion & 0xffff >= 3024))
OR ((##microsoftversion / power(2, 24) = 10)
AND (##microsoftversion & 0xffff >= 1600))))
SELECT #VarDecimalSupported = 1;
IF (#VarDecimalSupported > 0)
BEGIN
EXECUTE sp_db_vardecimal_storage_format N'$(DatabaseName)', 'ON';
END
GO
PRINT N'Update complete.';
GO
DROP TRIGGER EPI_BOREHOLE_INI;
CREATE OR REPLACE TRIGGER EPI_BOREHOLE_INI
INSTEAD of Insert ON EPI_BOREHOLE for each row
DECLARE
V_ID number(10);
V_USER varchar2(100);
BEGIN
if (:new.UBHI is null or :new.NAME is null or) then
Raise_Application_Error(-20101, 'Insert failed. The key values of BOREHOLE(UBHI, NAME) cannot be null');
end if;
begin
select BOREHOLE_ID.nextval into V_ID from dual;
SELECT USER INTO V_USER FROM DUAL;
INSERT INTO EPI_BOREHOLE (ID, UBHI, NAME, INSERT_DATE ,INSERT_NAME, UPDATE_DATE,UPDATE_NAME) VALUES (V_ID,:NEW.UBHI, :NEW.NAME, SYSDATE, V_USER, SYSDATE, V_USER);
end;
END;
I see little error in your code: Please see below:
if (:new.UBHI is null or :new.NAME is null or) then <-- An additional OR written.
remove it and try or put one more condition.
I dont see any issue with the code.
Try doing
SET DEFINE OFF
My work colleague is making the ASP.NET Web Forms application collecting data. I'm administrating SQL Server database of it. Based on databse he makes objects to Web Forms using Linq to SQL. He wanted me to make recodrds in Osoby to change dataDodania with date of generation the object and dataModyfikacji with date of last update. Having experience in PL/SQL I made simple triggers for this. The problem is that triggers work when I run SQL statements in SQL Server Management Studio 2008 nicely, but when used in application - they are omitted, not making changes needed. Here is triggers SQL code:
CREATE TRIGGER [dbo].[DodanieOsoby]
ON [dbo].[Osoby]
INSTEAD OF INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO Osoby(dataDodania, dataModyfikacji, loginId, rola, imie, imieDrugie, nazwisko, plec, wiek,pESEL,wyksztalcenie,opieka,ulica, nrDom, nrLokal, miejscowosc, obszar, kodPoczty, telefonKontakt, telefonStacjo, email, zatrudnienie, stanowisko, przedsiebiorstwo)
SELECT GETDATE(), GETDATE(), loginId, rola, imie, imieDrugie, nazwisko, plec, wiek, pESEL, wyksztalcenie,opieka,ulica, nrDom, nrLokal, miejscowosc, obszar, kodPoczty, telefonKontakt, telefonStacjo, email, zatrudnienie, stanowisko, przedsiebiorstwo
FROM inserted
END
And for UPDATE of Osoby...
CREATE TRIGGER [dbo].[AktualizacjaOsoby]
ON [dbo].[Osoby]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE Osoby
SET dataModyfikacji = GETDATE()
WHERE id in
(SELECT DISTINCT id from Inserted)
END
Possible this be helpful for you (if dbo.Osoby is view) -
ALTER TRIGGER dbo.trg_IOIU_vw_WorkOut
ON dbo.vw_WorkOut
INSTEAD OF INSERT, UPDATE
AS BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON
DECLARE
#WorkOutID BIGINT
, #DateOut DATETIME
, #EmployeeID INT
DECLARE workout CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
SELECT
WorkOutID
, DateOut
, EmployeeID
FROM INSERTED
OPEN workout
FETCH NEXT FROM workout INTO
#WorkOutID
, #DateOut
, #EmployeeID
WHILE ##FETCH_STATUS = 0 BEGIN
IF NOT EXISTS(
SELECT 1
FROM dbo.WorkOut
WHERE WorkOutID = #WorkOutID
)
BEGIN
INSERT INTO dbo.WorkOut
(
EmployeeID
, DateOut
)
SELECT
#EmployeeID
, #DateOut
SELECT SCOPE_IDENTITY() -- if you use LINQ need return new ID to client
END
ELSE BEGIN
UPDATE dbo.WorkOut
SET
EmployeeID = #EmployeeID
, DateOut = #DateOut
WHERE WorkOutID = #WorkOutID
END
FETCH NEXT FROM workout INTO
#WorkOutID
, #DateOut
, #EmployeeID
END
CLOSE workout
DEALLOCATE workout
END
I need to automate the following set of instructions with a pl/sql procedure:
SET DEFINE OFF;
TRUNCATE TABLE EMP.dept;
INSERT INTO EMP.dept values....;
Commit;
Also,I need to log the activity(sucess/failure) into a table EMP.Log.
Can someone help me in this ?
Depending on what the columns are in the EMP.dept table I would use a procedure defined as:
--The parameters to this procedure depend on the fields in EMP.dept
--This example assumes EMP.dept has only 2 VARCHAR fields, but
--the parameter list can easily be modified:
--
CREATE OR REPLACE PROCEDURE PROC_NAME1(INPUT1 IN VARCHAR2, INPUT2 IN VARCHAR2) AS
V_FAILURE INTEGER;
BEGIN
V_FAILURE := 0;
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE EMP.dept';
INSERT INTO EMP.dept (FIELD1, FIELD2) VALUES (INPUT1, INPUT2);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
V_FAILURE := 1;
ROLLBACK;
END;
BEGIN
--DEPENDING ON THE COLUMNS IN YOUR LOG_TABLE
--
INSERT INTO LOG_TABLE(STATUS, RUN_DATE)
VALUES (V_FAILURE, SYSDATE);
COMMIT;
EXCEPTION
WHEN OTHERS THEN NULL;
END;
END;