Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





How Do I Make Use Of Begin Transaction And Commit Transaction In SSIS.


Hi

 

How do I make use of begin transaction and commit transaction in SSIS.

As am not able to commit changes due to certain update commands I want to explicitly write begin and commit statements. but when i make use of begin and commit in OLEDB commnad stage it throws an error as follows:

Hresult:0x80004005

descriptionyntax error or access violation.

 

its definately not an syntax error as i executed it in sql server. also when i use it in execute sql task out side the dataflow container it doesnt throw any error but still this task doesnt serve my purpose of saving/ commiting update chanages in the database.

 

Thanks,

Prashant




View Complete Forum Thread with Replies

Related Forum Messages:
Usage Of Begin Transaction.... Commit Transaction??
Hi, anyone can help,I am trying to learn how to use begin tran..commit tran .. rollback tran by doing this exercise... unfortunatelly,it did not work...anyone can help...
I have a table named tbl_balance(investor_id int,amount money)
I want to insert/update balance for each investor. I wrote a procedure but it didnot work:::

declare @investorid int, @amount money,@error_status int
select @investorid=1
select @amount = 500
/* to check if investor exist in the tbl_balance table, if so execute the codes */
IF exists(select investorid from tbl_bal where investorid=@investorid )
begin tran
begin
update tbl_balance
set amount=amount+@amount
where investorid =@investorid

if (@error_status<> 0)
begin
ROLLBACK tran
select 'you did not update'
end
else
begin
COMMIT tran
select ' YOu did update '
end
end

IF not exists(select investorid from tbl_bal where investorid=@investorid )
begin tran
begin
insert into tbl_balance
values(@investorid,@amount)

if (@error_status<> 0)
begin
ROLLBACK tran
select 'you did not update'
end
else
begin
COMMIT tran
select ' YOu did update '
end
end

View Replies !
BEGIN TRANSACTION COMMIT TRANSACTION Help
I had thought that if any statement failed within a BEING TRANS .. COMMIT TRANS block, then all the statements would be rolled back. But I am seeing different behavior (SQL Server 2000 8.00.2039)

For instance, run these statements to set up a test:
--DROP TABLE testTable1
--DROP TABLE testTable2
CREATE TABLE testTable1 (f1 varchar(1))
CREATE TABLE testTable2 (f1 varchar(1))
CREATE UNIQUE INDEX idx_tmptmp ON testTable1 (f1)
insert into testTable1(f1) values ('a')

So table testTable1 has a unique index on it..

Now try to run these statements:

--DELETE FROM testTable2
BEGIN TRANSACTION
insert into testTable1(f1) values ('a')
insert into testTable2(f1) values ('a')
COMMIT TRANSACTION

SELECT * FROM testTable2


..the first insert fails on the unique index.. but the second insert succeeds. Shouldn't the second insert roll back? How can I make two operations atomic?

View Replies !
BEGIN TRANSACTION And COMMIT TRANSACTION
I am executing a stored procedure something like this

Create Procedure TEST
@test1
@test2
AS
BeGIN TRANSACTION ONE
SELECT...
UPDATE..
....
....

....
TRUNCATE
etc and lot of Select,update and delete statements like this
.....
COMMIT TRANSACTION ONE


The Block of code which I have b/w BEGIN TRANSACTION AND COMMIT TRANSACTION ..Will it be rolled back
if it encounters any errors in the SELECT,UPPDATE,DELETE ..statements which I have with the transaction one.
IF not How do I roll back if it encounters any erros b/w the BEGIN TRANSACTION and END TRANSACTION.

Thanks
micky

View Replies !
BEGIN And COMMIT Transaction
Can help me?
I have to insert BEGIN and COMMIT Transaction in my stored procedure (call to a trigger)





Code Snippet

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

ALTER                                             PROCEDURE [dbo].[DETTAGLIO_TURNI_DIFENSORI]

(
@tipo_albo VARCHAR(50),
@data_inizio DATETIME,
@data_fine DATETIME,
@descrizione VARCHAR(50),
@idturno INT,
@n_dif INT
)

AS


-- DICHIARAZIONE VARIABILI...
DECLARE @dett_idturno as INT
DECLARE @totale_giorni as INT
DECLARE @tipo_albo_A as VARCHAR(9)
DECLARE @tipo_albo_B as VARCHAR(9)
DECLARE @data_odierna as DATETIME
DECLARE @tot_avvocati as INT
DECLARE @avv_giorno as INT
DECLARE @avv_giornoA as INT
DECLARE @avv_giornoB as INT
DECLARE @conta_giorni as INT
DECLARE @incremento_giorni as INT
DECLARE @incr_dif_giorno as INT
DECLARE @nuovo_idturno as INT
DECLARE @idalboturno as INT
DECLARE @old_turni as INT
DECLARE @tot_giorniA as INT
DECLARE @tot_giorniB as INT
DECLARE @conta_giorni_incremento as INT
DECLARE @conta_avvocati as INT
DECLARE @avv as INT
DECLARE @altri_turni AS INT
DECLARE @neg_giorni_incremento as int
-------------------------------------------------------------------------------------------------------

-- SET VARIABILI PER EVITARE PROBLEMI CON NULL o 0
SET @totale_giorni = 0
SET @tot_avvocati = 0
SET @avv_giorno = 0
SET @conta_giorni = 0
SET @incremento_giorni = 0
SET @incr_dif_giorno = 0
SET @idalboturno = 0
SET @old_turni = 0
--------------------------------------------------------------------------------------------------------

SET @nuovo_idturno = @idturno

BEGIN TRAN

-- conta i giorni
SELECT @totale_giorni = (DATEDIFF(dd, @data_inizio, @data_fine))+1

-- select da vista avvocati per tipo difensori selezionato.. (controllare anche data_fine_iscrizione?)

    create table #Tmp   
    (
    [ID_anagrafica] varchar(50)
    )

IF @tipo_albo = 'DIFO'
BEGIN
    SET @tipo_albo_A = 'DIFM'
    SET @tipo_albo_B = 'CPT'
   
    -- select per contare..
   
    SELECT @tot_avvocati = COUNT(*)
    FROM VALBO_ISCRIZIONE_DIF_ORDINARI
   
    SELECT @tot_avvocati As tot_avvocati

    -- creo tabella temporanea..
    INSERT INTO #Tmp
    SELECT [ID_anagrafica]
    FROM VALBO_ISCRIZIONE_DIF_ORDINARI ORDER BY ID_ANAGRAFICA   

END

IF @tipo_albo = 'DIFM'
BEGIN
    SET @tipo_albo_A = 'DIFO'
    SET @tipo_albo_B = 'CPT'

    -- select per contare..
    SELECT @tot_avvocati = COUNT(*)
    FROM VALBO_ISCRIZIONE_DIF_MINORI
   
    SELECT @tot_avvocati as tot_avvocati

    -- creo tabella temporanea..
    INSERT INTO #Tmp
    SELECT [ID_anagrafica]
    FROM VALBO_ISCRIZIONE_DIF_MINORI ORDER BY ID_ANAGRAFICA   
END

IF @tipo_albo = 'CPT'
BEGIN
    SET @tipo_albo_A = 'DIFM'
    SET @tipo_albo_B = 'DIFO'
   
    -- select per contare..
    SELECT @tot_avvocati = COUNT(*)
    FROM VALBO_ISCRIZIONE_DIF_CPT
   
    SELECT @tot_avvocati as tot_avvocati
   
    INSERT INTO #Tmp
    SELECT [ID_anagrafica]
    FROM VALBO_ISCRIZIONE_DIF_CPT ORDER BY ID_ANAGRAFICA   
END
 
DECLARE @idanagrafica varchar(50)

-- GIORNI PER AVVOCATO
-- tot_giorni * n_dif_minimo / tot_avvocati = tot_giorni_avvocato (con intero successivo)
SET @incremento_giorni = ((@totale_giorni * @n_dif)/@tot_avvocati)
-- controllo se c'è resto..
IF ((@totale_giorni * @n_dif)%@tot_avvocati) <> 0
BEGIN
    SET @incremento_giorni = @incremento_giorni + 1
END

-- ogni avvocato deve essere difensore per almeno 2 giorni di seguito..
-- quindi se l'incremento è minore di 2 deve essere uguale a 2
IF @incremento_giorni < '2'
BEGIN
     SET @incremento_giorni = '2'
END

-- AVVOCATI AL GIORNO
-- numero variabile.. prendere in considerazione il primo intero e l'intero successivo..
SET @avv_giorno = (@incremento_giorni * @tot_avvocati)/@totale_giorni
SET @avv_giornoB = @avv_giorno

-- controllo il resto della divisione.. se <> 0 @avv_giornoB = @avv_giorno + 1..
-- altrimenti i due valori sono uguali..

IF ((@incremento_giorni * @tot_avvocati)%@totale_giorni) <> 0
BEGIN
    SET @avv_giornoA = @avv_giorno + 1
END
ELSE
BEGIN
    set @avv_giornoA = @avv_giorno
END

-- conteggi giorni totali difensori...
-- giorni con N difensori
SET @tot_giorniB = ((@avv_giornoB * @incremento_giorni)/@totale_giorni)
-- giorni con M difensori
SET @tot_giorniA = @totale_giorni - @tot_giorniB

declare @totale as int
declare @conta_inseriti as int
set @conta_inseriti = 0
set @totale = (@avv_giornoA * @tot_giorniA) + (@avv_giornoB * @tot_giorniB)

-- ciclo per totale dei giorni
SET @conta_giorni = 1
SET @conta_giorni_incremento = 0
SET @conta_avvocati = 0
WHILE @conta_giorni <= @totale_giorni BEGIN
   
    -- ogni giorno @avv deve essere ZERO
    SET @avv = 0
   
    IF @conta_giorni <= @tot_giorniA
    BEGIN   
         SET @avv_giorno = @avv_giornoA
        END
        ELSE
        BEGIN   
         SET @avv_giorno = @avv_giornoB
        END
   
    -- ciclo per ogni giorno per totale di avvocati/giorno
    SET @incr_dif_giorno = 0
   
    WHILE (@incr_dif_giorno < @avv_giorno) AND EXISTS(SELECT TOP 1 ID_anagrafica FROM #Tmp) BEGIN

        SET @conta_avvocati = @conta_avvocati + 1   
   
        SET @data_odierna = DATEADD(dd, (@conta_giorni-1), @data_inizio)

        SET @neg_giorni_incremento = -1 * @conta_giorni_incremento

        SET @old_turni = 0
        SET @altri_turni = 0
 
            SELECT TOP 1 @idanagrafica = ID_anagrafica from #Tmp
            DELETE #Tmp WHERE ID_anagrafica = @idanagrafica

            -- query che controlla i turni già assegnati per altre liste...

            SELECT @old_turni = COUNT(*)
            FROM Albo_Turno_Dettaglio CROSS JOIN
               ALBO_TURNO
            WHERE
               Albo_Turno_Dettaglio.idalbo = @idanagrafica
            AND
              (
              ALBO_TURNO.Tipo = @tipo_albo_A   --- probabile problema con trigger
            OR
              ALBO_TURNO.Tipo = @tipo_albo_B
            )
            AND
              (
               Albo_Turno_Dettaglio.Data
            BETWEEN
              DATEADD(dd, (@neg_giorni_incremento + 1), @data_odierna)
            AND
              DATEADD(dd, (@incremento_giorni-@conta_giorni_incremento), @data_odierna)
             )

                SELECT @old_turni AS old_turni

            -- (nel caso in cui il ciclo ricominci..) controllare che questo avvocato non abbia
            -- già un set di giorni in questo turno...

            -- passato il primo controllo.. deve passare anche questo..
                   
            SELECT @altri_turni = COUNT(*)
            FROM Albo_Turno_Dettaglio
            WHERE
            Albo_Turno_Dettaglio.idalbo = @idanagrafica
            AND
            Albo_Turno_Dettaglio.idturno = @nuovo_idturno        
       
            SELECT @altri_turni AS altri_turni

            IF @old_turni = NULL
            BEGIN
            SET @old_turni = 0
            END
           
            IF @ALTRI_TURNI = NULL
            BEGIN
            SET @ALTRI_TURNI = 0
            END
       
            IF (@old_turni = 0 AND (@altri_turni = 0 OR @altri_turni < (@incremento_giorni)))
            BEGIN
                       -- se non ci sono turni sovraposti assegna il turno all'avvocato x N giorni (incremento_giorni)
                      -- seleziono il dettaglio con idturno max per aumentare di uno...           
                SET @idalboturno = 1
                SET @dett_idturno = 1
                SELECT @dett_idturno = MAX(idalboturno)
                FROM Albo_Turno_Dettaglio
           
                if (@dett_idturno) = null
                begin
                    set @dett_idturno = 0
                end
       
                  SET @idalboturno = @dett_idturno + 1

BEGIN TRAN

                  INSERT Albo_Turno_Dettaglio
                  (
                    idalboturno,
                   idalbo,
                    idturno,
                    data
                  )
                  VALUES
                  (
                     @idalboturno,
                     @idanagrafica, -- da cursore
                     @nuovo_idturno,
                     @data_odierna -- problemi inserimento data??
                  )
               
COMMIT
                  -- valorizza il numero degli avvocati del giorno + 1
                      SET @incr_dif_giorno = @incr_dif_giorno + 1
            END
            ELSE
            BEGIN
                  -- non incrementare la variabile...
                SET @incr_dif_giorno = @incr_dif_giorno
                END
       
        END -- END WHILE AVVOCATI PER GIORNI

        SET @conta_giorni_incremento = (@conta_giorni_incremento + 1)
             IF @conta_giorni_incremento < @incremento_giorni
             BEGIN
            --DEVO RIPOPOLARE LA TABELLA PERCHE' OGNI AVVOCATO DEVE AVERE X GIORNI..
            -- cancello tutti i record e poi inserisco di nuovo..       
            DELETE FROM #Tmp
            IF @tipo_albo = 'DIFO'
            BEGIN

                INSERT INTO #Tmp
                SELECT [ID_anagrafica]
                FROM VALBO_ISCRIZIONE_DIF_ORDINARI ORDER BY ID_ANAGRAFICA   
            END

            IF @tipo_albo = 'DIFM'
            BEGIN

                INSERT INTO #Tmp
                SELECT [ID_anagrafica]
                FROM VALBO_ISCRIZIONE_DIF_MINORI ORDER BY ID_ANAGRAFICA   
            END

            IF @tipo_albo = 'CPT'
            BEGIN
           
                INSERT INTO #Tmp
                SELECT [ID_anagrafica]
                FROM VALBO_ISCRIZIONE_DIF_CPT ORDER BY ID_ANAGRAFICA   
            END

             END
        ELSE
             BEGIN
            set @conta_giorni_incremento = 0
             END           

        SET @conta_giorni = @conta_giorni + 1
END
 
DROP TABLE #TMP

COMMIT TRAN


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

View Replies !
TRANSACTIONS In SSIS (error: The ROLLBACK TRANSACTION Request Has No Corresponding BEGIN TRANSACTION.&&"
I'm receiving the below error when trying to implement Execute SQL Task.

"The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION." This error also happens on COMMIT as well and there is a preceding Execute SQL Task with BEGIN TRANSACTION tranname WITH MARK 'tran'

I know I can change the transaction option property from "supported" to "required" however I want to mark the transaction. I was copying the way Import/Export Wizard does it however I'm unable to figure out why it works and why mine doesn't work.

Anyone know of the reason?

View Replies !
Using Begin Transaction,End Transaction, Return,Rollback, Break,Continue
Hi, is there someone who can demonstrate the usgae of these codes in this simple process. I have a table that has (id int, Balance money)
I want to write codes to utilize the Subject coding in this process.
1.Every time I withdraw money from a client, I want to verrify that he/she has enough money if not I want to roll back transaction.
2.Using Begin Tran , end Tran..
3. Using Return ,Break,continue

I really appreciate your help. Althought I read about this from a book, but it really confused me and I want to see real world example using client and withdraw from there accounts...:)

regards
Ali

View Replies !
How To Create A Transaction Commit/Rollback For Oracle DB In SSIS
 I'm able to connect to the Oracle database to insert the data into multiple tables using OLEDB connection via Oracle Provider for OLEDB. However, i wish to create a transaction so that i'm able to rollback all the data in the case where the insertion fails in one of the table. May i know where should i start from?

View Replies !
BEGIN TRANSACTION Or BEGIN DISTRIBUTED TRANSACTION
Hi have have two linked SQL Servers and I am trying to get things workingsmootly/quickly.Should I be using 'BEGIN TRANSACTION' or 'BEGIN DISTRIBUTED TRANSACTION' ?Basicly, these SPs update a local table and a remote table in the sametransaction. I cant have one table updated and not the other. Please dontsay replicate the tables either as at this time, this is is not an option.I have for example a number of stored procedures that are based around thefollowing:where ACSMSM is a remote (linked) SQL Server.procedure [psm].ams_Update_VFE@strResult varchar(8) = 'Failure' output,@strErrorDesc varchar(512) = 'SP Not Executed' output,@strVFEID varchar(16),@strDescription varchar(64),@strVFEVirtualRoot varchar(255),@strVFEPhysicalRoot varchar(255),@strAuditPath varchar(255),@strDefaultBranding varchar(16),@strIPAddress varchar(23)asdeclare @strStep varchar(32)declare @trancount intSet XACT_ABORT ONset @trancount = @@trancountset @strStep = 'Start of Stored Proc'if (@trancount = 0)BEGIN TRANSACTION mytranelsesave tran mytran/* start insert sp code here */set @strStep = 'Write VFE to MSM'updateACSMSM.msmprim.msm.VFECONFIGsetDESCRIPTION = @strDescription,VFEVIRTUALROOT = @strVFEVirtualRoot,VFEPHYSICALROOT = @strVFEPhysicalRoot,AUDITPATH = @strAuditPath,DEFAULTBRANDING = @strDefaultBranding,IPADDRESS = @strIPAddresswhereVFEID = @strVFEID;set @strStep = 'Write VFE to PSM'updateACSPSM.psmprim.psm.VFECONFIGsetDESCRIPTION = @strDescription,VFEVIRTUALROOT = @strVFEVirtualRoot,VFEPHYSICALROOT = @strVFEPhysicalRoot,AUDITPATH = @strAuditPath,DEFAULTBRANDING = @strDefaultBranding,IPADDRESS = @strIPAddresswhereVFEID = @strVFEID/* end insert sp code here */if (@@error <> 0)beginrollback tran mytranset @strResult = 'Failure'set @strErrorDesc = 'Fail @ Step :' + @strStep + ' Error : ' + @@Errorreturn -1969endelsebeginset @strResult = 'Success'set @strErrorDesc = ''end-- commit tran if we started itif (@trancount = 0)commit tranreturn 0

View Replies !
SSIS, Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
I have a design a SSIS Package for ETL Process. In my package i have to read the data from the tables and then insert into the another table of same structure.

for reading the data i have write the Dynamic TSQL based on some condition and based on that it is using 25 different function to populate the data into different 25 column. Tsql returning correct data and is working fine in Enterprise manager. But in my SSIS package it show me time out ERROR.

I have increase and decrease the time to catch the error but it is still there i have tried to set 0 for commandout Properties.

if i'm using the 0 for commandtime out then i'm getting the Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.

and

Failed to open a fastload rowset for "[dbo].[P@@#$%$%%%]". Check that the object exists in the database.

Please help me it's very urgent.

View Replies !
Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.
With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean        Dim bSuccess As Boolean        Dim MyConnection As SqlConnection = GetConnection()        Dim cmd As New SqlCommand("", MyConnection)        Dim i As Integer        Dim fBeginTransCalled As Boolean = False
        'messagetype 1 =internal messages        Try            '            ' Start transaction            '            MyConnection.Open()            cmd.CommandText = "BEGIN TRANSACTION"            cmd.ExecuteNonQuery()            fBeginTransCalled = True            Dim obj As Object            For i = 0 To MessageIDs.Count - 1                bSuccess = False                'delete userid-message reference                cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID"                cmd.Parameters.Add(New SqlParameter("@UserID", UserID))                cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString))                cmd.ExecuteNonQuery()                'then delete the message itself if no other user has a reference                cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1"                cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString))                obj = cmd.ExecuteScalar                If ((Not (obj) Is Nothing) _                AndAlso ((TypeOf (obj) Is Integer) _                AndAlso (CType(obj, Integer) > 0))) Then                    'more references exist so do not delete message                Else                    'this is the only reference to the message so delete it permanently                    cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2"                    cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString))                    cmd.ExecuteNonQuery()                End If            Next i
            '            ' End transaction            '            cmd.CommandText = "COMMIT TRANSACTION"            cmd.ExecuteNonQuery()            bSuccess = True            fBeginTransCalled = False        Catch ex As Exception            'LOG ERROR            GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message)        Finally            If fBeginTransCalled Then                Try                    cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection)                    cmd.ExecuteNonQuery()                Catch e As System.Exception                End Try            End If            MyConnection.Close()        End Try        Return bSuccess    End Function

View Replies !
Begin And End Transaction And Transaction Log
Hello everyone,This is more of an architectural question about SQL Server. Cansomeone please explain why when I perform a query such as the onebelow that updates a table using begin and end transaction I am unableto programmatically truncate the transaction log. The only way I havefound to truncate the transaction log is to stop and start the SQLServer Service. Does this transaction use the tempdb? Is that why Iam unable to truncate the transaction log? Is there a better way todo this?Begin trans T1Update sometableSet random_row = 'blah'End trans T1Thanks!

View Replies !
Begin Transaction In Asp.net
Hi All,Can any one help by giving me the details/difference in using the Transaction Isolation Levels (read uncommitted, read committed, repeatable read, or serializable)in asp.net. I just want to know in which case we can use these things in begining a transaction, and will it improve the performance. thanks in advance Boo

View Replies !
Begin Transaction
Could someone tell me if this is the correct way to begin and commit a transaction:

CREATE procedure AddTitle
@title varchar(255),
@descriptions varchar(255),
@mediaId int,
@quantityowned int,
@classificationid int


AS
BEGIN Tran TranStart

Set NOCOUNT ON
declare @titleid int --declaring the titleid


INSERT INTO Titles(title, [descriptions])
values(@title,
@descriptions)


set @titleid = SCOPE_IDENTITY() --grabbing the id to be placed in the other table


INSERT INTO Resources(titleid,mediaid,quantityowned)
values(@titleid,
@mediaid,
@quantityowned)

insert into titleclassification(titleid, classificationid)
values(@titleid, @classificationid)

select @titleid as titleid -- return to caller if needed

Commit Tran Transtart
GO

Where would I put rollback transaction? Do I need it?

Thanks!

View Replies !
Use Of Begin/End Transaction
I need to copy two large tables from one database into another, via the internet. I haven't worked out exactly how yet, but the first issue which has occurred to me is that by the time the first table has been exported (via a SELECT clause?) into a suitable file, the second table (to which it is related) will be out of sync. So, how do I ensure that I end up with a snapshot of the two tables, perfectly in sync with each other? I know that BEGIN/END TRANSACTION makes sure that UPDATES to tables remain in sync, but will it work just for SELECT statements?

View Replies !
C# SQLTransaction Or SQL BEGIN TRANSACTION
I want to know if it's a good practice to use sql-transaction in both c# and sql procedures code.

View Replies !
Where Should I BEGIN/END Transaction? In Code Or In The SP?
I notice you can do a END and BEGIN trasaction in BOTH. But I hope BOTH are not needed. So where so I use them  ?
 
Or should I even use them for simple updates and inserts ?

View Replies !
Deadlocks && BEGIN/END TRANSACTION
Greetings,I've been reading with interest the threads here on deadlocking, as I'mfinding my formerly happy app in a production environment suddenlydeadlocking left and right. It started around the time I decided towrap a series of UPDATE commands with BEGIN/END.The gist of it is I have a .NET app that can do some heavy reading (nowriting) from tblWOS. It can take a minute or so to read all the datainto the app, along with data from other tables.I also have a web app out on the floor where people can entertransactions which updates perhaps 5-20 records in tblWOS at a time.The issue comes when someone is loading data with the app, and someoneelse tries an update through the web app: deadlocks-ville on theapplication and/or the web app.Again, I believe it began around the time I wrapped those 5-20 recordupdates to tblWOS on the web app with BEGIN/END. The funny thing isthat the records involved are not the same ones, so I'm thinking somekind of table-level lock is going on.I've played with UPDLOCK in examples, but don't quite understand whatit's attempting to do. Since the web update is discrete and short, andit is NOT updating records that are getting loaded, I'd like theBEGIN/UPDATE/END web transaction to happen and not deadlock the loadingapplication.Any suggestions? I'd be most grateful.thanks, Leaf

View Replies !
BEGIN DISTRIBUTED TRANSACTION
Hi

I am using MSDTC and RPC to transfer data from one server to other.

It was working fine since last day but today my procedure is getting stuck at BEGIN DISTRIBUTION TRANSACTION command.

Any idea why?

Manish

View Replies !
COMMIT TRANSACTION
How can i work with the commit transaction if i am using asp.net 2.0 with SQLDataSource?

View Replies !
How To Commit The Transaction
hi friends,

Iam Executing the sp logic.suppose incase if any problem occurs inbetween execution(NO SPACE,communication failure,log full)
data is getting commited partially insteady of rollbacking entire transaction.

CREATE procedure RBI_Control_sp
as
begin

set nocount on
--Checking the count before truncating
exec fin_ods..count_sp

--Truncating the Table
exec fin_ods..trun_sp

--Data Transfer
exec fin_ods..RBI_Data_Transfer_sp

--Checking the count after Data transfer
exec fin_ods..count_sp

--temp table Table population,Fetching data from the fin_ods[erp Table]
exec FIN_wh..RBI_SPExecution_sp

set nocount off
end

View Replies !
Unable To Begin A Distributed Transaction
I have this code
 DECLARE @tempTableName VarChar(50)SET @tempTableName = NEWID()
CREATE TABLE #@tempTableName( State Char(2), Billed Money, AslCode VarChar(10))INSERT INTO #@tempTableName EXEC GetRecords '2/1/2008'
which gives me this error when I run
The operation could not be performed because the OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction.[OLE/DB provider returned message: New transaction cannot enlist in the specified transaction coordinator. ]OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ITransactionJoin::JoinTransaction returned 0x8004d00a].
GetRecords does a select * from a linked server's table. Which is working fine but if I try to do an insert (into temp table) then I get the error.
Any help?

View Replies !
Unable To Begin A Distributed Transaction
Having a SQL Server 2K (SP3a) with a link to another SQL Server 2K (noservice packs), distributed transactions works as expected most of thetime.But occasionally the MSDTC(s) seems to fall in a state of failure,causing the following error when involving distributed transactions:"The operation could not be performed because the OLE DB provider'SQLOLEDB' was unable to begin a distributed transaction.[OLE/DB provider returned message: New transaction cannot enlist inthe specified transaction coordinator. ]OLE DB error trace [OLE/DB Provider 'SQLOLEDB'ITransactionJoin::JoinTransaction returned 0x8004d00a]."The only way out of this state is to stop and start both of the SQLServers (stop/start of the DTC's doesn't help).Is this a common problem?Guess I will be recommended to install SP on the server withoutservice packs, but will this positively solve the problem describedabove?Could general network failures cause the error state described above,and if so - is there a way to make the MSDTC's survive or recover fromthe error situation automatically?--Morten Haugen

View Replies !
Unable To Begin A Distributed Transaction
I am using MSDASQL provider to create a linkedServer and is using Distrubuted Transaction in the application...but it is throwing out the following error...

Server: Msg 7391, Level 16, State 1, Line 1
The operation could not be performed because the OLE DB provider 'MSDASQL' was unable to begin a distributed transaction.
[OLE/DB provider returned message: [Microsoft][ODBC SQL Server Driver]Distributed transaction error]
OLE DB error trace [OLE/DB Provider 'MSDASQL' ITransactionJoin::JoinTransaction returned 0x8004d00a].


What keeps me guessing is that the same code worked in the development environment and had no problems in starting the Distributed Transaction...

Note: DTC is running on both the server and I am not using a loop back server!!!!


Please Help

View Replies !
Transaction In Packages; When Do They Commit?
Hello,
 
I am a SSIS developer from the Netherlands. I have a question about the use of a transaction in a package.
I have a Sequence container with some data flow tasks and some SQL tasks. The TransactionOption for this container is set to Required. The transactionOption for the tasks in the container are set to Supported. After this container I have put some other tasks (like a script task and an send mail task). This last 2 tasks have a TransactionOption set to Not Supported.
I have done this this way because if something goes wrong in the Sequence Container everthing in this container will be rollbacked. This work fine! But if one of the last 2 task goes wrong (the tasks after the container) everthing in the container is also rollbacked. I don't know why this is happening. Can you help me with this?
 
Thanks! Greetings, Pieter.

View Replies !
Commit Transaction Logic
Hai, in Sql server 2000 database, i want to do the following..
from my UI, i will be updating one table(only 3 columns among the table columns), But the number of records will be around 2000 to 2500.
So every 200th record, i want to commit the transaction, so that i cannot lose the data..
Using query can i achieve this? or do i need to use the simple while loop logic.
Pls advise me

View Replies !
Unable To Begin A Distributed Transaction (Msg 7391)
I am receiving the following error when I run a stored procedure:Server: Msg 7391, Level 16, State 1, Procedure spXXXXThe SP inserts data into a local (sql 2000) table from a remote sql2000 database. The SP works fine until I add a trigger to thedestination. The contents of the trigger do not appear to matter, as Ihave tried removing everything but one line, which is just a declarestatement. Updating the table with the trigger (even the full trigger)in place does not cause an error. Running the SP without the triggeron the table does not cause the error.I have the exact same setup on another server. Both the SP and thetrigger are IDENTICAL. This setup works on one server, but not theother. The only difference I can see is that the non-working server isWindows 2000 Server, while the working server is Windows 2003 Server.Any idea what's going on here?Thanks in advance.Eric

View Replies !
Begin Tran In An Sp Executed Fom Within A Transaction Scope
we have an update sp that must call an insert sp after the update.  The update and insert must act like a transaction, ie all or none.
 
We believe that wrapping most of the update (including call to insert sp) sp in a begin tran block would guarantee the all or none behavior.
 
However, we're not sure what would happen if one of our developers calls the update sp from within a transaction scope that expects yet something additional to be included in the transaction.  Would the begin tran block (assuming no errors in that block) in the sp commit both the update and insert regardless of what happens in the rest of the .net tran scope?       

View Replies !
'SQLOLEDB' Was Unable To Begin A Distributed Transaction
SQL2000 / W2K
 

I'm having issues with a query to a view that references a view on a linked server, that in turn references a view on a third server.
 
Query to view on Server A -->  View on Server B  -->  View on Server C
 
I can query from A to B using the linked server.
I can query from B to C.
I can query from A to C.
 
All servers at the same location on the same domain.
 
I cannot query a view on A, that references a view on B, where the view on B references a view/table on C
 
Each linked server configuration uses "Be made using this security context", with the user specified being 'sa'.  I was hoping to get security out of the equation for debug purposes, hence the sa use.
 
I have tried from Query Analyzer using both windows and sql auth.
 
MSDTC is running on all servers as local system.
 
The full error returned is:
 
Server: Msg 7391, Level 16, State 1, Line 1
The operation could not be performed because the OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction.
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ITransactionJoin::JoinTransaction returned 0x8004d00a].
[OLE/DB provider returned message: New transaction cannot enlist in the specified transaction coordinator. ]
 
 
 
Thanks for any support,
 
Chris
 
 
 
 
 

View Replies !
Commit Fail And Transaction Log Is Full
Hi,

Our testing server experienced a timeout exception when execute  System.Data.SqlClient.SqlTransaction.Commit() in SQL Server 2000 thru .Net Framework 1.1. And this happened at 2007-02-13 18:07:05,954.
It was strange to us that all the insert statement can be executed without error within the transaction but the commit operation fails.
Moreover, after about 40 minutes, we found that the transaction log of this database is full.

Here is the exception and SQL Server 2000 Error Log:
Exception Stack Trace:
DateTime:   2007-02-13 18:07:05,954
Req Id:     bccdae08-cc47-4f85-8f48-5f0b9dbbbf88
Exception:  MyDatabaseException
Detail:    
MyDatabaseException:
Index #0
Server: MySQLServer
Source: .Net SqlClient Data Provider
Message: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
LineNumber: 0
Procedure: ConnectionRead (recv()).
State: 0
Error Number: -2 ---> System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, TdsParserState state)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.ReadNetlib(Int32 bytesExpected)
   at System.Data.SqlClient.TdsParser.ReadBuffer()
   at System.Data.SqlClient.TdsParser.ReadByte()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior run, SqlCommand cmdHandler, SqlDataReader dataStream)
   at System.Data.SqlClient.SqlInternalConnection.ExecuteTransaction(String sqlBatch, String method)
   at System.Data.SqlClient.SqlConnection.ExecuteTransaction(String sqlBatch, String method)
   at System.Data.SqlClient.SqlTransaction.Commit()


SQL Server Error Log:

2007-02-13 13:02:23.72 backup    Database backed up: Database: MyDatabaseName, creation date(time): 2007/01/12(12:01:39), pages dumped: 944769, first LSN: 9434:22326:1, last LSN: 9434:22360:1, number of dump devices: 1, device information: (FILE=1, TYPE=DISK: {'E:MSSQLBackupMyDatabaseName.bak'}).
2007-02-13 15:50:52.40 backup    Database backed up: Database: MyDatabaseName, creation date(time): 2007/01/12(12:01:39), pages dumped: 944970, first LSN: 9442:38096:1, last LSN: 9443:748:1, number of dump devices: 1, device information: (FILE=1, TYPE=VIRTUAL_DEVICE: {'Legato#4f96edfd-7fdb-4cd1-a740-3fe9a54d66c6'}).
2007-02-13 18:48:51.42 spid66    Error: 9002, Severity: 17, State: 62007-02-13 18:48:51.42 spid66    The log file for database 'MyDatabaseName' is full. Back up the transaction log for the database to free up some log space..
2007-02-13 18:52:40.61 spid58    Error: 9002, Severity: 17, State: 6
2007-02-13 18:52:40.61 spid58    The log file for database 'MyDatabaseName' is full. Back up the transaction log for the database to free up some log space..
2007-02-13 18:53:22.69 spid61    Error: 9002, Severity: 17, State: 6
2007-02-13 18:53:22.69 spid61    The log file for database 'MyDatabaseName' is full. Back up the transaction log for the database to free up some log space..
2007-02-13 18:54:01.11 spid57    Error: 9002, Severity: 17, State: 6
2007-02-13 18:54:01.11 spid57    The log file for database 'MyDatabaseName' is full. Back up the transaction log for the database to free up some log space..



Are these 2 things related? Would a full transaction log cause a commit operation fail?

Please kindly advice.

Thanks a lot.

View Replies !
Transaction Commit Doesn't Work
Could somebody also help me on the issue:  I am using OLE DB to setup database with SQL CE 3.1, what i need is to flush the buffer to database file before program exit, I am using DBPROPVAL_SSCE_TCM_FLUSH and Transaction commit, but they don't work for me,  My code is here:
 
1. the code to do transaction commit
 

// Access Transaction Interface

hr = pIDBCreateCommand->QueryInterface(IID_ITransactionLocal, (void **) &pTransLocal);

ULONG lTransLevel;

// Start the transaction

hr = pTransLocal->StartTransaction( ISOLATIONLEVEL_READCOMMITTED, 0, NULL, &lTransLevel );

// Execute the command with paramters.

hr = pICommandText->Execute(NULL, IID_NULL, &params, &cRowsAffected, NULL);

if( FAILED( hr ) )

{

goto Exit;

}

// commit

hr = pTransLocal->Commit( FALSE, XACTTC_SYNC, 0 );

pTransLocal->Release();

 
 
2. the code to set up property:
 

void LogDatabase::SetSessionProperty( IDBCreateSession *pISession )

{

DBPROPSET dbpropset[1]; // Property Set used to initialize provider

DBPROP sessionProps[1];

VariantInit(&sessionProps[0].vValue);

ISessionProperties *pISessionProperties = NULL;

//************** We Initial a session properties here *************

// Initialize a session object.

HRESULT hr = pISession->CreateSession(NULL, IID_ISessionProperties,

(IUnknown**) &pISessionProperties);

// Initialize the property to change commit mode.

sessionProps[0].dwPropertyID = DBPROP_SSCE_TRANSACTION_COMMIT_MODE;

sessionProps[0].dwOptions = DBPROPOPTIONS_REQUIRED;

sessionProps[0].vValue.vt = VT_I4;

sessionProps[0].vValue.lVal = DBPROPVAL_SSCE_TCM_FLUSH;

 

// Initialize the session property set.

dbpropset[0].guidPropertySet = DBPROPSET_SSCE_SESSION;

dbpropset[0].rgProperties = sessionProps;

dbpropset[0].cProperties = sizeof(sessionProps)/sizeof(sessionProps[0]);

// Set the session property.

hr = pISessionProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),

dbpropset);

VariantClear(&sessionProps[0].vValue);

}

View Replies !
Problem With SSIS Transaction...Transaction Scope
 

Hi,

I am having some problem with SSIS transaction. Eventhought I tried to imitate the concept that Jamie presented at http://www.sqlservercentral.com/columnists/jthomson/transactionsinsqlserver2005integrationservices.asp

. My workflow is as followed

*********************************
For Each ADO.Record in Oracle (transaction=not supported)

If (Certain_Field_Value = 'A')


Lookup Data in SQL DB with values from Oracle (transaction=not supported)

DO Sequence A (Start a Transaction , transaction=required)


INSERT/UPDATE some records in SQLDB(transaction=supported)
Finish Sequence A ( transaction should stop here)
UPDATE Oracle DB ( Execute SQLTask, transaction=not supported)
If (Certain_Field_Value = 'B')


Lookup Data in SQL DB with values from Oracle (transaction=not supported)

DO Sequence B (Start a Transaction , transaction = required)


INSERT/UPDATE some records in SQLDB (transaction=supported)
Finish Sequence A ( transaction should stop here)
UPDATE Oracle DB ( Execute SQLTask, transaction=not supported)
If (Certain_Field_Value = 'C')

------------
------------
End ForEach Loop
*************************************
My requirements are that I want separate transaction for each Sequence A, B, C, etc... If Sequence A transaction fails, the other should still be continuing with another transaction.
But I am getting an error regarding the OLEDB Error in next Task (e.g in Certain_Field_Value = 'B') "Lookup Data in SQL DB with values from Oracle ", the error message is  ".......Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction. ".
What is it that I am doing wrong?
Regards
KyawAM

View Replies !
Transaction Scope - The Operation Could Not Be Performed Because OLE DB Provider &"SQLNCLI&" For Linked Server &"XXX_LINKED_SERVER&" Was Unable To Begin A Distributed Transaction. OLE DB Provider &"SQLNCLI&a
Hello, I've a problem with a software developed in C# with the framework 2.0. This is the error I receive : The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "XXX_LINKED_SERVER" was unable to begin a distributed transaction. OLE DB provider "SQLNCLI" for linked server "XXX_LINKED_SERVER" returned message "No transaction is active.". If I try directly to restart the process, it works fine. Is there someone who can help me ? This is the process 1. In C# --> Call of a Query : select from the linked server (db in sql 2005) and insert into a table SQL 2005 2. In the C# --> using (TransactionScope scope = new TransactionScope()) and insert in a table in SQL 2005 which is link server Thank in advance.

View Replies !
'MSDAORA' Was Unable To Begin A Distributed Transaction - Why?! (SQL &<-&> Oracle)
Hello!I have an Oracle linked server connected through MSDAORA. Linked serverqueries work perfectly - the "openquery" ones as well as the4-part-named ones.The problem I have is with embedding the queries within SQL Servertriggers.Trigger:CREATE TRIGGER tgTest ON [dbo].[test]FOR INSERT, UPDATE, DELETEASselect * from openquery(LS, 'select * from ORACLE_TEST')executing "delete from test" in SQL Query Analyzer raises this error:Server: Msg 7391, Level 16, State 1, Procedure tgTest, Line 5The operation could not be performed because the OLE DB provider'MSDAORA' was unable to begin a distributed transaction.OLE DB error trace [OLE/DB Provider 'MSDAORA'ITransactionJoin::JoinTransaction returned 0x8004d01b].I've tried almost every solution I found online, but nothing helped:(This looked promissing: http://tinyurl.com/nk2wd , but it didn't get meany futher.Maybe someone can get me through the troubleshoot mentioned in thatlink:- check if DTC running properlyHow do I check that? If I open the "Support services" in EnterpriseManager and right-click the "Distributed Transaction Coordinatior" Ican stop the service, what indicates the service is running, but isthere anything else I should check? I have 0 items in the right windowpane of the DTC item, is it OK?- registry setting as discussed earlierThe following Registry Keys should be entered:[HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSDTCMTxOCI ]"OracleXaLib"="oraclient8.dll""OracleSqlLib"="orasql8.dll""OracleOciLib"="oci.dll"My entries are:"OracleOciLib"="ociw32.dll""OracleSqlLib"="SQLLib18.dll""OracleXaLib"="xa73.dll"Are they OK?- check if Mtxoci.dll is loadedThere is a Mtxoci.dll in my system32 dir, but how do I tell if it'sloaded? Should I regsvr32 it?- SET XACT_ABORT ON should be use in your SQL statement, for example:SET XACT_ABORT ONBEGIN DISTRIBUTED TRANSELECT statementCOMMIT TRANI've tried that, both in trigger but also surrounding the query thatfires the trigger.Am getting deseperate - please help. Will send candies!TIA

View Replies !
Linked Server And Unable To Begin A Distributed Transaction
I have a database containing my own tables and data and I wanted tobe able to query this against an accountancy program which has an ODBCdriver. This was never a problem with MS Access and Jet but I hit Jet'slimitations and have moved to SQL.Creating my own SQL database was no problem, but I was unsure of thebest way to be able to be able to have my SQL tables and my accountancysoftware tables appearing in the same Access front end.I created a linked server to the accountancy program. This wassuccessful in that I could see all the tables below the linked server inenterprise manager.My problem occurs when I try to bring the data from these tablesinto my SQL database.I create a new view in my database:-SELECT *FROM OPENQUERY(SAGE_SERVER, 'SELECT * FROM STOCK')(My linked server is called 'SAGE_SERVER' and I am trying to retrieveall columns from the STOCK table.)I then try to save this view and get the following errors.ODBC Error: [Microsoft][ODBC SQL Server Driver][SQL Server]The operationcould not be performed because the OLE DB provider 'MSDASQL' was unableto begin a distributed transaction.[Microsoft][ODBC SQL Server Driver][SQL Server]OLE DB Error Trace[OLE/DBProvider 'MSDASQL' ITransactionJoi JoinTransaction returned 0x8004d00a].Thanks in advance,Marcus Thornton.

View Replies !
OLE DB Provider 'MSDAORA' Was Unable To Begin A Distributed Transaction
Dear all,

I have been attempting to set up a linked server in SQL Server 2000 to point to an Oracle database (a very old Oracle database, v7!).

The linked server set up works fine. Then I created a database on the same SQL Server. Within that database I created a view which reads information from a view in the Oracle database (linked server). When I attempted to create this view in Enterprise Manager, I get the following error:

"The operation could not be performed because the OLE DB provider 'MSDAORA' was unable to begin a distributed transaction."

And so I created the view in Query Analyzer. This worked perfectly, no errors, and I can now go into Enterprise Manager and call up the view, which happily goes off to the view in the Oracle linked server and pulls back the info. BUT, when I attempt to do the same thing through an application on a different machine (using OLE Db, and a UDL to connect) the same error as above appears.

Does anyone know what this error means, and where I went wrong? Any help greatly appreciated. My view onto the linked server looks like this:

"CREATE VIEW dbo.NLPG_VIEW
AS
SELECT * from openquery(sadaslink, 'select * from NLPG_VIEW')"

Many thanks in advance for your wisdom!

P.S I wondered whether I need to check if the distributed transaction co-ordinator is running but don't know how.
Thanks,

View Replies !
Insert ... Exec Unable To Begin A Distributed Transaction
I have 3 development SQL Servers A, B & C, all running SQL 2000 sp3 and Windows 2003. Servers B & C have a linked server pointing to A, and A has one pointing to B & C. The linkedservers all have RPC , RPC out enabled. I have a stored procedure called test on server A.

Create Proc test
as

Select Top 5 first_name, last_name from people

GO


--code ran on Servers B & C:

create table #tmptbl (nm varchar(100), nm2 varchar(100))

insert into #tmptbl
Exec ServerA.db1.dbo.test


When the Insert....Exec code above is ran from server B it works fine, however when I run it from Server C, I get error 7391
The operation could not be performed because the OLE DB provider 'SQLOLEDB' was unable to begin a distributed transaction.
[OLE/DB provider returned message: New transaction cannot enlist in the specified transaction coordinator. ]
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ITransactionJoin::JoinTransaction returned 0x8004d00a]

But regular linked server calls (directly to tables) and openquery calls work fine from either server...

Eg
insert into #tmp
Select top 5 first_name, last_name from ServerA.db1.dbo.people

--and this works also

insert into #tmp
Select * from openquery(ServerA, 'Exec db1.dbo.test')


Both servers (B & C) appear to be configured the same, and
I have reconfigured MSDTC on all three boxes through control panel and component manager, have tried using SET xact_abort, SET implicit_transactions, registry hacks (TurnoffRPCsecurity), basically everything listed on Microsoft, and everything I've been able to find in these groups.

If anyone has any ideas, I'd like to hear them.

Tim.

View Replies !
Error 266 - I'm Confused, Only One Transaction With COMMIT And ROLLBACK
I have a transaction that calls one other sproc and also executes another set of queries, but for some reason I'm getting error 266: "Msg 266, Level 16, State 2, Procedure AddUserHaveTag, Line 26.  Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing.  Previous count = 0, current count = 1."There is NO transaction in the sproc AddTag.  It is also included below.Here is the sproc with the transaction:1 set ANSI_NULLS ON2 set QUOTED_IDENTIFIER ON
3 go4
5 ALTER PROCEDURE [dbo].[AddUserHaveTag] 6 (7 @UserHaveID int,8 @Tag varchar(24),9 @UserHaveTagExists bit OUTPUT
10 )11 AS12 SET NOCOUNT OFF13 DECLARE @ErrorCode int14 DECLARE @TagID int15 DECLARE @TagExists bit16
17 BEGIN TRAN
18 19 -- Call proc to add tag to Tags table
20 EXEC AddTag @Tag, @TagID OUTPUT, @TagExists OUTPUT
21
22 -- Check for errors
23 IF @ErrorCode <> 0 GOTO ERROR24
25 -- Check for existing record, otherwise insert
26 IF EXISTS (SELECT 1 FROM UserHaveTags WHERE UserHaveID = @UserHaveID AND TagID = @TagID)27 BEGIN28 SET @UserHaveTagExists = 129 RETURN 030 END31 ELSE32 BEGIN33 INSERT INTO UserHaveTags (UserHaveID, TagID) VALUES (@UserHaveID, @TagID)34 SET @UserHaveTagExists = 035 END
36
37 -- Check for errors
38 IF @ErrorCode <> 0 GOTO ERROR39
40 COMMIT TRAN
41
42 ERROR:43 IF (@ErrorCode <> 0)44 BEGIN45 PRINT 'Unexpected error occurred!'
46 ROLLBACK TRAN47 END
  Here is the AddTag sproc:1 set ANSI_NULLS ON2 set QUOTED_IDENTIFIER ON
3 go4
5 ALTER PROCEDURE [dbo].[AddTag] 6 (7 @Tag varchar(24),8 @TagID int OUTPUT,9 @TagExists bit OUTPUT
10 )11 AS12 SET NOCOUNT OFF13 14 IF EXISTS (SELECT 1 FROM Tags WHERE Tag = @Tag)15 BEGIN16 SELECT @TagID = TagID FROM Tags WHERE Tag = @Tag17 SET @TagExists = 118 RETURN 019 END20 ELSE21 BEGIN22 INSERT INTO Tags (Tag) VALUES (@Tag)23 SET @TagID = SCOPE_IDENTITY()24 SET @TagExists = 025 ENDAny advice?Also if you see any glaring errors or things I could be doing better, I'm open to suggestions. I'm fairly new to sprocs and transactions. Thanks,Travis  

View Replies !
ADO.NET Transaction Fails To Update Database After .Commit()
SQL Server 2000, C#, ASP.NET and ADO.NET. I have searched for 3 days trying to figure out why my ADO.NET Transaction executes my stored procedures and runs the .COMMIT() on the server, figured this out by using the SQL Profiler, but the data doesn't show up in the database tables and I recieve no error from SQL or ASP.NET. What gives???? Anyone else ever heard of such a thing. Please help, before I loose my sanity.

View Replies !
Commit Transaction Gets Deleted - Unable To Save SP
I've re-written a stored procedure and when I post the following codeinto the existing SP in EM, is saves OK. However, when I re-edit theSP, the last line 'Commit Transaction' has been removed.I cannot save the remainder of the SP as it throws error 208 (InvalidObject name #Max) about two of the temp tables I use when I post theentire script. It shows in a message box with the header : 'MicrosoftSQL-DMO(ODBC SQLState:42S02)I haven't posted the full SP nor the structure as it's quite large(2000 lines), so hopefully I have given enough detail, but my questionsare :Why does it now have problems with (temp) #Tables ? The use of thesehas not changed. All I have done is wrap the script into varioustransactions as this helps a lot for performance and tweaked a fewparts later in the SP again for performance.Also, why does the line get removed once I save the SP ?If I run this in QA, I get the same errors, so I suspect it's myscript, but don't know where I'm going wrong.SQL2000 (Need to upgrade the service pack as recently installed on myPC, so this may help)Thanks in advanceRyanCREATE PROCEDURE [dbo].[JAG_Extract] (@ExtractYear INTEGER,@ExtractMonth INTEGER) ASBEGIN TRANSACTIONSELECT 0 AS MaxYear, 0 AS MaxMonth INTO #MaxUPDATE #Max SET MaxYear = @ExtractYearUPDATE #Max SET MaxMonth = @ExtractMonthPRINT 'Stage 1 - ' + Convert(VarChar, GetDate())CREATE TABLE #Extract ([DEALER_SOURCE_DATA_ID] INT,[DSD_YEAR] INT NULL,[DSD_MONTH] INT NULL,[DEALER_CODE] VarChar(20),[FranDealerCode] VarChar(20) NULL,[Line_No] VarChar(75),[Current] [numeric](15, 5) NULL,[YTD] [numeric](15, 5) NULL,[12Months] [numeric](15, 5) NULL,[24Months] [numeric](15, 5) NULL,[Average_YTD] [numeric](15, 5) NULL,[Average12Months] [numeric](15, 5) NULL,[Average24Months] [numeric](15, 5) NULL,[Last_YTD] [numeric](15, 5) NULL,[Current_STATUS] INT,[PD1] [numeric](15, 5) NULL,[PD2] [numeric](15, 5) NULL,[PD3] [numeric](15, 5) NULL,[PD4] [numeric](15, 5) NULL,[PD5] [numeric](15, 5) NULL,[PD6] [numeric](15, 5) NULL,[PD7] [numeric](15, 5) NULL,[PD8] [numeric](15, 5) NULL,[PD9] [numeric](15, 5) NULL,[PD10] [numeric](15, 5) NULL,[PD11] [numeric](15, 5) NULL,[PD12] [numeric](15, 5) NULL,[PD13] [numeric](15, 5) NULL,[PD14] [numeric](15, 5) NULL,[PD15] [numeric](15, 5) NULL,[PD16] [numeric](15, 5) NULL,[PD17] [numeric](15, 5) NULL,[PD18] [numeric](15, 5) NULL,[PD19] [numeric](15, 5) NULL,[PD20] [numeric](15, 5) NULL,[PD21] [numeric](15, 5) NULL,[PD22] [numeric](15, 5) NULL,[PD23] [numeric](15, 5) NULL,[PD24] [numeric](15, 5) NULL,[PD25] [numeric](15, 5) NULL,[PD26] [numeric](15, 5) NULL,[PD27] [numeric](15, 5) NULL,[PD28] [numeric](15, 5) NULL,[PD29] [numeric](15, 5) NULL,[PD30] [numeric](15, 5) NULL,[PD31] [numeric](15, 5) NULL,[PD32] [numeric](15, 5) NULL,[PD33] [numeric](15, 5) NULL,[PD34] [numeric](15, 5) NULL,[PD35] [numeric](15, 5) NULL,[PD36] [numeric](15, 5) NULL)INSERT INTO #ExtractSELECT DISTINCTSD.DEALER_SOURCE_DATA_ID,SD.DSD_YEAR,SD.DSD_MONTH,DN.DEALER_CODE,DN.FRAN_DEALER_CODE,DV.FIELD_CODE,0,0,0,0,0,0,0,0,SD.STATUS,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0FROMDEALER_NAW DN WITH (NOLOCK)INNER JOIN DEALER_SOURCE_DATA SD WITH (NOLOCK)ON DN.DEALER_CODE = SD.DEALER_CODEINNER JOIN DEALER_SOURCE_DATA_VALUES_Current DV WITH (NOLOCK)ON SD.DEALER_SOURCE_DATA_ID = DV.DEALER_SOURCE_DATA_IDAND SD.STATUS < 4096INNER JOIN DEALER_FIXED_GROUP_RELATION GR WITH (NOLOCK)ON DN.DEALER_CODE = GR.DEALER_CODEAND GR.FIXED_GROUP_ID IN(11,12,13,14,15,16,17,18,23,42,43,44,45,46,47,48,4 9,50,51,52,53,54,55,56,57,58,59,60,61,106,109,110,111,1 12,113,114,115,130,131,132,133,134,135,136,137)GOCOMMIT TRANSACTION

View Replies !
Commit Transaction Between Sql2000 And Sql2005 Server
Are there any tips/techniques/issues when doing a begin tran and commit between a sql 2000 server/db and a sql 2005 server/db. Should you still use "set xact_abort on"? This will be a recordset of about 1-2000

View Replies !
Error 8525: Distributed Transaction Completed. Either Enlist This Session In A New Transaction Or The NULL Transaction.
Hi All
 
I'm getting this when executing the code below.  Going from W2K/SQL2k SP4 to XP/SQL2k SP4 over a dial-up link.
 
If I take away the begin tran and commit it works, but of course, if one statement fails I want a rollback.  I'm executing this from a Delphi app, but I get the same from Qry Analyser.
 
I've tried both with and without the Set XACT . . ., and also tried with Set Implicit_Transactions off.
 
set XACT_ABORT ON
Begin distributed Tran
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.TRANSACTIONMAIN
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.TRANSACTIONMAIN
 set REPFLAG = 0 where REPFLAG = 1 and DONE = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.WBENTRY
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.WBENTRY
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.FIXED
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.FIXED
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.ALTCHARGE
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.ALTCHARGE
 set REPFLAG = 0 where REPFLAG = 1
update OPENDATASOURCE('SQLOLEDB','Data Source=10.10.10.171;User ID=*****;Password=****').TRANSFERSTN.TSADMIN.TSAUDIT
 set REPFLAG = 0 where REPFLAG = 1
update TSADMIN.TSAUDIT
 set REPFLAG = 0 where REPFLAG = 1
COMMIT TRAN

 
It's got me stumped, so any ideas gratefully received.Thx

View Replies !
Rolling Back Transaction After .Commit() Runs Successfully
I have a page that runs a transaction correctly after a button click.
I want to allow someone to click a button that rolls back the transaction, after the transaction runs on the first button click.
I can also successfully roll back within the first button click.
 I'm getting a NullReference error when trying to access SqlTransaction.Rollback() outside the button click.
 If SqlTransaction.Commit() completes without error can SqlTransaction.Rollback() be called after?
I tried making 'trans' a more global variable and it still gave me the error.
Button Click 1:
Dim trans As SqlTransaction
trans = connection.BeginTransaction()
try
'run SQL Statement
trans.Commit()
Catch e As Exception
 trans.Rollback()
throw e
end try
 
Button Click 2:
trans.Rollback()
 

View Replies !
Distributed Transaction Coordinator UPDATE Then COMMIT Then ROLLBACK
Hello,
 
I am running the following from New Query in SQL Server 2005 management studio in an SQL Server 2005 instance on a separate machine.
 
I am updating a SQL Server 2000 database on a separate machine.  I execute each statement one at a time.
 


SET XACT_ABORT ON

BEGIN DISTRIBUTED TRANSACTION
 

SELECT @@TRANCOUNT
 

SELECT RIGHT(StudentID,LEN(StudentID)-LEN('TE2_'))

FROM [HQ-A4].TI_excentonlineDD.dbo.Student
 

SELECT * FROM [HQ-A4].TI_excentonlineDD.dbo.Student
 

UPDATE [HQ-A4].TI_excentonlineDD.dbo.Student

SET StudentID = RIGHT(StudentID,LEN(StudentID)-LEN('TE2_'))

WHERE StudentID LIKE 'TE2_%'
 

SELECT * FROM [HQ-A4].TI_excentonlineDD.dbo.Student
 

SELECT @@TRANCOUNT
 

COMMIT TRANSACTION

SET XACT_ABORT OFF
 
The update statement, updates an SQL Server 2000 database.
 
The query will run for 30 seconds.
I test the results with SELECT * FROM [HQ-A4].TI_excentonlineDD.dbo.Student
then COMMIT TRANSACTION.  All is good.
 
After the  COMMIT TRANSACTION,  I check my new expected dataset expected results by SELECT * FROM [HQ-A4].TI_excentonlineDD.dbo.Student. 
 
Next, I open SQL Server 2000 query analyzer (another session (should show only COMMITED data) and connect to the
target SQL Server 2000 database.
 
I run SELECT * FROM TI_excentonlineDD.  I get my new expected dataset expected results.  All is good.
I close Query Analyzer.
 
I close the SQL Server 2005 Management Studio.
 
The weird problem
-------------------------
If I wait 5 minutes or so, open a new New Query or Query Analyzer, then, next, run SELECT * FROM [HQ-A4].TI_excentonlineDD.dbo.Student or run SELECT * FROM  TI_excentonlineDD.dbo.Student, I get back my "old dataset re-appears" (my pre-COMMITED data).  This is bad.
 
I have repeated that same scenaro with both BEGIN DISTRIBUTED TRANSACTION and just BEGIN TRANSACTION
After a while, the "old dataset re-appears" problem still happens.   This is all bad.
 
Is some sort of internal-crash or timeout failure occurring?
Any ideas where I could start looking to resolve this problem?
 
Thanks.
 
AIMDBA
 
 
 

 

View Replies !
Error: COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Why?
Hello:
I am implimenting the creation of sequence numbers .I use an insert proc on a table that generates the numbers using an identity field:
procedure usp_createidentity

begin transaction

  insert into [tblOrderNumber] with  default values

rollback  ' done so no records in this table

select @OrderNumber = scope_identity()
 
I call this from another proc that inserts values into my order table:

 
procedure usp_Insert  @OrderNumber int
as

SET XACT_ABORT ON;

BEGIN TRY

  BEGIN TRANSACTION
 

     EXEC usp_GetNewOrderNumber @OrderNumber = @OrderNumber output
      INSERT INTO [dbo].[tblOrder] ([OrderNumber]) values (@orderNumber) ' inserts value from other stored proc

  
COMMIT TRANSACTION

END TRY

BEGIN CATCH

 if (XACT_STATE() = -1)

ROLLBACK TRANSACTION

else

if (XACT_STATE() = 1)

COMMIT TRANSACTION
 END CATCH
 
Here is the problem.   When I run  usp_Insert I get the following:  Error 266  Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.
 
This refers to the  usp_GetNewOrderNumber  that is called inside the other proc as shown above.
 
The problem does not happen if I put each statement in usp_Insert in its own try/catch. transaction statements.
 
Maybe it has something to do with the rollback call in the usp_getneworder. 
 
What do I need to do to get rid of this. problem and still run these within one try/catch trans statement set.
 
Thanks

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved