I have a very simple transaction question. (in sql server 2000, but I assume this applies to general db transactions.)
tblPrimaryKey
PkId
1
2
3
tblForeignKey
Id ForeignKey
---- -----
1 1
2 2
3 3
4 1
I have 2 tables, one of which refers to the other (tblForeingKey.ForeignKey refers to tblPrimaryKey.PkID). Now I have some logics that change the primary key tab by deleting and reinserting the key.
Once deleted, the database will act in an inconsistent state. I looked at my old script, where I first dropped the relationship and recreated it afterwards. But my question is this: I found out that the transaction is atomic, so an intra-consistent state of the transaction is allowed.
So, I think something like this should work:
BEGIN TRAN eg
DELETE tblPrimaryKey WHERE PkId = 3
INSERT INTO tblPrimaryKey SELECT 3
COMMIT TRAN eg
. - , ?
:
, .
, .
, ?
:
, . - , : sql script, , . , , . script .
, , , , . , , . sproc, , - , , .
CREATE PROC usp_SyncRecords
(
@tableName1 as nvarchar(255),
@tableName2 as nvarchar(255),
@joinClause as nvarchar(255),
@whereClause as nvarchar(1000)
)
AS
BEGIN
DECLARE @sqlClause nvarchar(4000)
DECLARE @curFieldName nvarchar(255)
DECLARE @sqlColumnCursorClause nvarchar(1000)
SET @sqlClause = 'UPDATE [' + @tableName1 + '] SET '
SET @sqlColumnCursorClause =
'DECLARE cur CURSOR FAST_FORWARD FOR SELECT name FROM syscolumns ' +
'WHERE id=' + CAST(object_id(@tableName2) as nvarchar(50))
EXEC sp_executeSql @sqlColumnCursorClause
OPEN cur
FETCH NEXT FROM CUR INTO @curFieldName
WHILE @@fetch_status <> -1
BEGIN
SET @sqlClause = @sqlClause + @curFieldName + '=' +
@tableName2 + '.' + @curFieldName + ','
FETCH NEXT FROM CUR INTO @curFieldName
END
CLOSE cur
DEALLOCATE cur
SET @sqlClause = LEFT(@sqlClause,LEN(@sqlClause) -1)
SET @sqlClause = @sqlClause + ' FROM [' + @tableName1 + '] INNER JOIN [' + @tableName2 + '] '
+ 'ON ' + @joinClause + ' WHERE ' + @whereClause
EXEC sp_executeSQL @sqlClause
END