Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. declare @tableName as nvarchar(50)='Document'
  2. declare @tableSchema as nvarchar(50)='EMP'
  3. declare @sourceTableName as nvarchar(50)='@table'
  4. declare @pKeyName as nvarchar(50)='DocumentId'
  5.  
  6. declare @resUpdate as nvarchar(max)=''
  7. declare @resInsertValues as nvarchar(max)=''
  8. declare @resInsertFields as nvarchar(max)=''
  9. declare @columnName as nvarchar(50)=''
  10.  
  11. declare columnCursor CURSOR for
  12. SELECT COLUMN_NAME
  13. FROM INFORMATION_SCHEMA.COLUMNS
  14. WHERE TABLE_NAME = @tableName AND TABLE_SCHEMA=@tableSchema
  15.  
  16. OPEN columnCursor;
  17.  
  18. FETCH NEXT FROM columnCursor INTO @columnName;
  19.  
  20. -- Check @@FETCH_STATUS to see if there are any more rows to fetch.
  21. WHILE @@FETCH_STATUS = 0
  22. BEGIN
  23. set @resUpdate= @resUpdate + @columnName+' = u.' + lower(left(@columnName,1)) + substring(@columnName,2,len(@columnName)-1) +',' + CHAR(13)
  24. set @resInsertFields= @resInsertFields + @columnName +','
  25. set @resInsertValues= @resInsertValues + 'i.' + lower(left(@columnName,1)) + substring(@columnName,2,len(@columnName)-1) +','
  26. -- This is executed as long as the previous fetch succeeds.
  27. FETCH NEXT FROM columnCursor INTO @columnName;
  28. END
  29.  
  30. CLOSE columnCursor;
  31. DEALLOCATE columnCursor;
  32.  
  33. 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)
  34. print 'insert into ' + @tableSchema + '.' + @tableName + '(' + substring(@resInsertFields,1,len(@resInsertFields)-1) + ')'
  35. print 'select top 1 ' + substring(@resInsertValues,1,len(@resInsertValues)-1) + char(13) + 'from ' + @pKeyName + ' i' + CHAR(13) + CHAR(13)
  36. print ' delete from ' + @tableSchema + '.' + @tableName + ' where ' + @tableSchema + '.' + @tableName + '.'+ @pKeyName + ' = @'+@pKeyName
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement