Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- declare @tableName as nvarchar(50)='Document'
- declare @tableSchema as nvarchar(50)='EMP'
- declare @sourceTableName as nvarchar(50)='@table'
- declare @pKeyName as nvarchar(50)='DocumentId'
- declare @resUpdate as nvarchar(max)=''
- declare @resInsertValues as nvarchar(max)=''
- declare @resInsertFields as nvarchar(max)=''
- declare @columnName as nvarchar(50)=''
- declare columnCursor CURSOR for
- SELECT COLUMN_NAME
- FROM INFORMATION_SCHEMA.COLUMNS
- WHERE TABLE_NAME = @tableName AND TABLE_SCHEMA=@tableSchema
- OPEN columnCursor;
- FETCH NEXT FROM columnCursor INTO @columnName;
- -- Check @@FETCH_STATUS to see if there are any more rows to fetch.
- WHILE @@FETCH_STATUS = 0
- BEGIN
- set @resUpdate= @resUpdate + @columnName+' = u.' + lower(left(@columnName,1)) + substring(@columnName,2,len(@columnName)-1) +',' + CHAR(13)
- set @resInsertFields= @resInsertFields + @columnName +','
- set @resInsertValues= @resInsertValues + 'i.' + lower(left(@columnName,1)) + substring(@columnName,2,len(@columnName)-1) +','
- -- This is executed as long as the previous fetch succeeds.
- FETCH NEXT FROM columnCursor INTO @columnName;
- END
- CLOSE columnCursor;
- DEALLOCATE columnCursor;
- print 'update ' + @tableSchema + '.' + @tableName + ' set ' + substring(@resUpdate,1,len(@resUpdate)-2) + CHAR(13) + 'from ' + @sourceTableName + ' u where ' + @tableSchema + '.' + @tableName + '.'+@pKeyName + ' = u.' + lower(left(@pKeyName,1)) + substring(@pKeyName,2,len(@pKeyName)-1) + CHAR(13) + CHAR(13)
- print 'insert into ' + @tableSchema + '.' + @tableName + '(' + substring(@resInsertFields,1,len(@resInsertFields)-1) + ')'
- print 'select top 1 ' + substring(@resInsertValues,1,len(@resInsertValues)-1) + char(13) + 'from ' + @pKeyName + ' i' + CHAR(13) + CHAR(13)
- print ' delete from ' + @tableSchema + '.' + @tableName + ' where ' + @tableSchema + '.' + @tableName + '.'+ @pKeyName + ' = @'+@pKeyName
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement