• Lunes 23 de Diciembre de 2024, 09:10

Autor Tema:  Comparacion De Campos  (Leído 3559 veces)

ElNapster

  • Moderador
  • ******
  • Mensajes: 727
    • Ver Perfil
Comparacion De Campos
« en: Lunes 16 de Octubre de 2006, 19:48 »
0
Tengo una duda, habra alguna forma de comparar CAMPOS de una TABLA de una BD compararlos contra otra tabla de otra bd y ver si existen los mismos campos con las mismas extructuras ?

 :blink:
"Somos lo que imaginamos ser"
-- --------------------------------------------------------------
-ElNapster
-Designer / Developer Software
-GuaTemALa



Salteador

  • Nuevo Miembro
  • *
  • Mensajes: 5
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #1 en: Martes 24 de Octubre de 2006, 04:17 »
0
Imagina que tienes un campo empleados y otro departamentos los dos tienen el campo numero de departamento.

Pues haces una join de las dos tablas uniendolos por ese campo. Imagina que en la tabla departamentos tiene un campo que es tipo de director si es en funciones en propiedad. quiere que te muestre los empleados que tienen director en propiedad.


SELECT NOMBRE_EMPLEADO
FROM TABLA_EMPLEADOS,TABLA_DEPARTAMENTO
WHERE TABLA_EMPLEADOS.NUMERODEPARTAMENTO=TABLA_DEPARTAMENTO.NUMERODEPARTAMENTO AND TIPODIRECTOR='FUNCIONES'
ORDER BY NOMBRE_EMPLEADO;

En los campos que se repitan en las dos tablas tienes que especificar de que tabla es el que comparas.

lencho

  • Miembro de PLATA
  • *****
  • Mensajes: 1076
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #2 en: Martes 24 de Octubre de 2006, 05:03 »
0
Citar
compararlos contra otra tabla de otra bd

Salteador !!!, nuestro amigo elnapster se refiere a la consulta tuya pero de dos base de datos DISTINTAS, no de la misma.

BYTE.
______________________________________________________________________________________
"No estoy de acuerdo con lo que dices, pero defenderé con mi vida tu derecho a expresarlo"

JuanK

  • Miembro de ORO
  • ******
  • Mensajes: 5393
  • Nacionalidad: co
    • Ver Perfil
    • http://juank.io
Re: Comparacion De Campos
« Respuesta #3 en: Martes 24 de Octubre de 2006, 05:35 »
0
Cita de: "Salteador"
Imagina que tienes un campo empleados y otro departamentos los dos tienen el campo numero de departamento.

Pues haces una join de las dos tablas uniendolos por ese campo. Imagina que en la tabla departamentos tiene un campo que es tipo de director si es en funciones en propiedad. quiere que te muestre los empleados que tienen director en propiedad.


SELECT NOMBRE_EMPLEADO
FROM TABLA_EMPLEADOS,TABLA_DEPARTAMENTO
WHERE TABLA_EMPLEADOS.NUMERODEPARTAMENTO=TABLA_DEPARTAMENTO.NUMERODEPARTAMENTO AND TIPODIRECTOR='FUNCIONES'
ORDER BY NOMBRE_EMPLEADO;

En los campos que se repitan en las dos tablas tienes que especificar de que tabla es el que comparas.
nada que ver.

Lo que requiere napster en ofracle se haria con un db link, pero ni idea en SQl Server.
[size=109]Juan Carlos Ruiz Pacheco
[/size]
Microsoft Technical Evangelist
@JuanKRuiz
http://juank.io

ElNapster

  • Moderador
  • ******
  • Mensajes: 727
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #4 en: Miércoles 25 de Octubre de 2006, 22:30 »
0
:(
aca les dejo , algo muy interesante para llevarlo acabo en sql
Código: Text
  1.  
  2. sp_CompareDB Transact-SQL Code
  3. --------------------------------------------------------------------------------
  4. Below is the Transact-SQL code for the sp_CompareDB stored procedure. See the accompanying article to learn how to use it.
  5.  
  6.  
  7.  
  8.  
  9.  
  10. USE Master
  11. GO
  12. IF EXISTS (SELECT * FROM sysobjects WHERE name = 'sp_CompareDB' and type = 'P')
  13. DROP PROC sp_CompareDB
  14. GO
  15. --------------------------------------------------------------------------------------------
  16. -- sp_CompareDB
  17. --
  18. -- The SP compares structures and data in 2 databases.
  19. -- 1. Compares if all tables in one database have analog (by name) in second database
  20. -- Tables not existing in one of databases won't be used for data comparing
  21. -- 2. Compares if structures for tables with the same names are the same. Shows structural
  22. -- differences like:
  23. -- authors
  24. -- Column Phone: in db1 - char(12), in db2 - char(14)
  25. -- sales
  26. -- Column Location not in db2
  27. -- Tables, having different structures, won't be used for data comparing. However if the tables
  28. -- contain columns of the same type and different length (like Phone in the example above) or
  29. -- tables have compatible data types (have the same type in syscolumns - char and nchar,
  30. -- varchar and nvarchar etc) they will be allowed for data comparing.
  31. -- 3. Data comparison itself.
  32. -- 3.1 Get information about unique keys in the tables. If there are unique keys then one of them
  33. -- (PK is a highest priority candidate for this role) will be used to specify rows with
  34. -- different data.
  35. -- 3.2 Get information about all data columns in the table and form predicates that will be
  36. -- used to compare data.
  37. -- 3.3 Compare data with the criteria:
  38. -- a. if some unique keys from the table from first database do not exist in second db (only
  39. -- for tables with a unique key)
  40. -- b. if some unique keys from the table from second database do not exist in first db (only
  41. -- for tables with a unique key)
  42. -- c. if there are rows with the same values of unique keys and different data in other
  43. -- columns (only for tables with a unique key)
  44. -- d. if there are rows in the table from first database that don't have a twin in the
  45. -- table from second db
  46. -- e. if there are rows in the table from second database that don't have a twin in the
  47. -- table from first db
  48. --------------------------------------------------------------------------------------------
  49. -- Parameters:
  50. -- 1. @db1 - name of first database to compare
  51. -- 2. @db2 - name of second database to compare
  52. -- 3. @TabList - list of tables to compare. if empty - all tables in the databases should be
  53. -- compared
  54. -- 4. @NumbToShow - number of rows with differences to show. Default - 10.
  55. -- 5. @OnlyStructure - flag, if set to 1, allows to avoid data comparing. Only structures should
  56. -- be compared. Default - 0
  57. -- 6. @NoTimestamp - flag, if set to 1, allows to avoid comparing of columns of timestamp
  58. -- data type. Default - 0
  59. -- 7. @VerboseLevel - if set to 1 allows to print querues used for data comparison
  60. --------------------------------------------------------------------------------------------
  61. -- Created by Viktor Gorodnichenko (c)
  62. -- Created on: July 5, 2001
  63. --------------------------------------------------------------------------------------------
  64. CREATE PROC sp_CompareDB
  65. @db1 varchar(128),
  66. @db2 varchar(128),
  67. @OnlyStructure bit = 0,
  68. @TabList varchar(8000) = '',
  69. @NumbToShow int = 10,
  70. @NoTimestamp bit = 0,
  71. @VerboseLevel tinyint = 0
  72. AS
  73. if @OnlyStructure <> 0
  74. set @OnlyStructure = 1
  75. if @NoTimestamp <> 0
  76. set @NoTimestamp = 1
  77. if @VerboseLevel <> 0
  78. set @VerboseLevel = 1
  79.  
  80. SET NOCOUNT ON
  81. SET ANSI_WARNINGS ON
  82. SET ANSI_NULLS ON
  83. declare @sqlStr varchar(8000)
  84. set nocount on
  85. -- Checking if there are specified databases
  86. declare @SrvName sysname
  87. declare @DBName sysname
  88. set @db1 = RTRIM(LTRIM(@db1))
  89. set @db2 = RTRIM(LTRIM(@db2))
  90. set @SrvName = @@SERVERNAME
  91. if CHARINDEX('.',@db1) > 0
  92. begin
  93. set @SrvName = LEFT(@db1,CHARINDEX('.',@db1)-1)
  94. if not exists (select * from master.dbo.sysservers where srvname = @SrvName)
  95. begin
  96. print 'There is no linked server named '+@SrvName+'. End of work.'
  97. return
  98. end
  99. set @DBName = RIGHT(@db1,LEN(@db1)-CHARINDEX('.',@db1))
  100. end
  101. else
  102. set @DBName = @db1
  103. exec ('declare @Name sysname select @Name=name from ['+@SrvName+'].master.dbo.sysdatabases where name = '''+@DBName+'''')
  104. if @@rowcount = 0
  105. begin
  106. print 'There is no database named '+@db1+'. End of work.'
  107. return
  108. end
  109. set @SrvName = @@SERVERNAME
  110. if CHARINDEX('.',@db2) > 0
  111. begin
  112. set @SrvName = LEFT(@db2,CHARINDEX('.',@db2)-1)
  113. if not exists (select * from master.dbo.sysservers where srvname = @SrvName)
  114. begin
  115. print 'There is no linked server named '+@SrvName+'. End of work.'
  116. return
  117. end
  118. set @DBName = RIGHT(@db2,LEN(@db2)-CHARINDEX('.',@db2))
  119. end
  120. else
  121. set @DBName = @db2
  122. exec ('declare @Name sysname select @Name=name from ['+@SrvName+'].master.dbo.sysdatabases where name = '''+@DBName+'''')
  123. if @@rowcount = 0
  124. begin
  125. print 'There is no database named '+@db2+'. End of work.'
  126. return
  127. end
  128.  
  129. print Replicate('-',LEN(@db1)+LEN(@db2)+25)
  130. print 'Comparing databases '+@db1+' and '+@db2
  131. print Replicate('-',LEN(@db1)+LEN(@db2)+25)
  132. print 'Options specified:'
  133. print ' Compare only structures: '+CASE WHEN @OnlyStructure = 0 THEN 'No' ELSE 'Yes' END
  134. print ' List of tables to compare: '+CASE WHEN LEN(@TabList) = 0 THEN ' All tables' ELSE @TabList END
  135. print ' Max number of different rows in each table to show: '+LTRIM(STR(@NumbToShow))
  136. print ' Compare timestamp columns: '+CASE WHEN @NoTimestamp = 0 THEN 'No' ELSE 'Yes' END
  137. print ' Verbose level: '+CASE WHEN @VerboseLevel = 0 THEN 'Low' ELSE 'High' END
  138.  
  139. -----------------------------------------------------------------------------------------
  140. -- Comparing structures
  141. -----------------------------------------------------------------------------------------
  142. print CHAR(10)+Replicate('-',36)
  143. print 'Comparing structure of the databases'
  144. print Replicate('-',36)
  145. if exists (select * from tempdb.dbo.sysobjects where name like '#TabToCheck%')
  146. drop table #TabToCheck
  147. create table #TabToCheck (name sysname)
  148. declare @NextCommaPos int
  149. if len(@TabList) > 0
  150. begin
  151. while 1=1
  152. begin
  153. set @NextCommaPos = CHARINDEX(',',@TabList)
  154. if @NextCommaPos = 0
  155. begin
  156. set @sqlstr = 'insert into #TabToCheck values('''+@TabList+''')'
  157. exec (@sqlstr)
  158. break
  159. end
  160. set @sqlstr = 'insert into #TabToCheck values('''+LEFT(@TabList,@NextCommaPos-1)+''')'
  161. exec (@sqlstr)
  162. set @TabList = RIGHT(@TabList,LEN(@TabList)-@NextCommaPos)
  163. end
  164. end
  165. else -- then will check all tables
  166. begin
  167. exec ('insert into #TabToCheck select name from '+@db1+'.dbo.sysobjects where type = ''U''')
  168. exec ('insert into #TabToCheck select name from '+@db2+'.dbo.sysobjects where type = ''U''')
  169. end
  170. -- First check if at least one table specified in @TabList exists in db1
  171. exec ('declare @Name sysname select @Name=name from '+@db1+'.dbo.sysobjects where name in (select * from #TabToCheck)')
  172. if @@rowcount = 0
  173. begin
  174. print 'No tables in '+@db1+' to check. End of work.'
  175. return
  176. end
  177. -- Check if tables existing in db1 are in db2 (all tables or specified in @TabList)
  178. if exists (select * from tempdb.dbo.sysobjects where name like '#TabNotInDB2%')
  179. drop table #TabNotInDB2
  180. create table #TabNotInDB2 (name sysname)
  181. insert into #TabNotInDB2
  182. exec ('select name from '+@db1+'.dbo.sysobjects d1o '+
  183. 'where name in (select * from #TabToCheck) and '+
  184. ' d1o.type = ''U'' and not exists '+
  185. '(select * from '+@db2+'.dbo.sysobjects d2o'+
  186. ' where d2o.type = ''U'' and d2o.name = d1o.name)')
  187. if @@rowcount > 0
  188. begin
  189. print CHAR(10)+'The table(s) exist in '+@db1+', but do not exist in '+@db2+':'
  190. select * from #TabNotInDB2
  191. end
  192. delete from #TabToCheck where name in (select * from #TabNotInDB2)
  193. drop table #TabNotInDB2
  194.  
  195. if exists (select * from tempdb.dbo.sysobjects where name like '#TabNotInDB1%')
  196. drop table #TabNotInDB1
  197. create table #TabNotInDB1 (name sysname)
  198. insert into #TabNotInDB1
  199. exec ('select name from '+@db2+'.dbo.sysobjects d1o '+
  200. 'where name in (select * from #TabToCheck) and '+
  201. ' d1o.type = ''U'' and not exists '+
  202. '(select * from '+@db1+'.dbo.sysobjects d2o'+
  203. ' where d2o.type = ''U'' and d2o.name = d1o.name)')
  204. if @@rowcount > 0
  205. begin
  206. print CHAR(10)+'The table(s) exist in '+@db2+', but do not exist in '+@db1+':'
  207. select * from #TabNotInDB1
  208. end
  209. delete from #TabToCheck where name in (select * from #TabNotInDB1)
  210. drop table #TabNotInDB1
  211. -- Comparing structures of tables existing in both dbs
  212. print CHAR(10)+'Checking if there are tables existing in both databases having structural differences ...'+CHAR(10)
  213. if exists (select * from tempdb.dbo.sysobjects where name like '#DiffStructure%')
  214. drop table #DiffStructure
  215. create table #DiffStructure (name sysname)
  216. set @sqlStr='
  217. declare @TName1 sysname, @TName2 sysname, @CName1 sysname, @CName2 sysname,
  218. @TypeName1 sysname, @TypeName2 sysname,
  219. @CLen1 smallint, @CLen2 smallint, @Type1 sysname, @Type2 sysname, @PrevTName sysname
  220. declare @DiffStructure bit
  221. declare Diff cursor fast_forward for
  222. select d1o.name, d2o.name, d1c.name, d2c.name, d1t.name, d2t.name,
  223. d1c.length, d2c.length, d1c.type, d2c.type
  224. from ('+@db1+'.dbo.sysobjects d1o
  225. JOIN '+@db2+'.dbo.sysobjects d2o2 ON d1o.name = d2o2.name and d1o.type = ''U'' --only tables in both dbs
  226. and d1o.name in (select * from #TabToCheck)
  227. JOIN '+@db1+'.dbo.syscolumns d1c ON d1o.id = d1c.id
  228. JOIN '+@db1+'.dbo.systypes d1t ON d1c.xusertype = d1t.xusertype)
  229. FULL JOIN ('+@db2+'.dbo.sysobjects d2o
  230. JOIN '+@db1+'.dbo.sysobjects d1o2 ON d1o2.name = d2o.name and d2o.type = ''U'' --only tables in both dbs
  231. and d2o.name in (select * from #TabToCheck)
  232. JOIN '+@db2+'.dbo.syscolumns d2c ON d2c.id = d2o.id
  233. JOIN '+@db2+'.dbo.systypes d2t ON d2c.xusertype = d2t.xusertype)
  234. ON d1o.name = d2o.name and d1c.name = d2c.name
  235. WHERE (not exists
  236. (select * from '+@db2+'.dbo.sysobjects d2o2
  237. JOIN '+@db2+'.dbo.syscolumns d2c2 ON d2o2.id = d2c2.id
  238. JOIN '+@db2+'.dbo.systypes d2t2 ON d2c2.xusertype = d2t2.xusertype
  239. where d2o2.type = ''U''
  240. and d2o2.name = d1o.name
  241. and d2c2.name = d1c.name
  242. and d2t2.name = d1t.name
  243. and d2c2.length = d1c.length)
  244. OR not exists
  245. (select * from '+@db1+'.dbo.sysobjects d1o2
  246. JOIN '+@db1+'.dbo.syscolumns d1c2 ON d1o2.id = d1c2.id
  247. JOIN '+@db1+'.dbo.systypes d1t2 ON d1c2.xusertype = d1t2.xusertype
  248. where d1o2.type = ''U''
  249. and d1o2.name = d2o.name
  250. and d1c2.name = d2c.name
  251. and d1t2.name = d2t.name
  252. and d1c2.length = d2c.length))
  253. order by coalesce(d1o.name,d2o.name), d1c.name
  254. open Diff
  255. fetch next from Diff into @TName1, @TName2, @CName1, @CName2, @TypeName1, @TypeName2,
  256. @CLen1, @CLen2, @Type1, @Type2
  257. set @PrevTName = ''''
  258. set @DiffStructure = 0
  259. while @@fetch_status = 0
  260. begin
  261. if Coalesce(@TName1,@TName2) <> @PrevTName
  262. begin
  263. if @PrevTName <> '''' and @DiffStructure = 1
  264. begin
  265. insert into #DiffStructure values (@PrevTName)
  266. set @DiffStructure = 0
  267. end
  268. set @PrevTName = Coalesce(@TName1,@TName2)
  269. print @PrevTName
  270. end
  271. if @CName2 is null
  272. print '' Colimn ''+RTRIM(@CName1)+'' not in '+@db2+'''
  273. else
  274. if @CName1 is null
  275. print '' Colimn ''+RTRIM(@CName2)+'' not in '+@db1+'''
  276. else
  277. if @TypeName1 <> @TypeName2
  278. print '' Colimn ''+RTRIM(@CName1)+'': in '+@db1+' - ''+RTRIM(@TypeName1)+'', in '+@db2+' - ''+RTRIM(@TypeName2)
  279. else --the columns are not null(are in both dbs) and types are equal,then length are diff
  280. print '' Colimn ''+RTRIM(@CName1)+'': in '+@db1+' - ''+RTRIM(@TypeName1)+''(''+
  281. LTRIM(STR(CASE when @TypeName1=''nChar'' or @TypeName1 = ''nVarChar'' then @CLen1/2 else @CLen1 end))+
  282. ''), in '+@db2+' - ''+RTRIM(@TypeName2)+''(''+
  283. LTRIM(STR(CASE when @TypeName1=''nChar'' or @TypeName1 = ''nVarChar'' then @CLen2/2 else @CLen2 end))+'')''
  284. if @Type1 = @Type2
  285. set @DiffStructure=@DiffStructure -- Do nothing. Cannot invert predicate
  286. else
  287. set @DiffStructure = 1
  288. fetch next from Diff into @TName1, @TName2, @CName1, @CName2, @TypeName1, @TypeName2,
  289. @CLen1, @CLen2, @Type1, @Type2
  290. end
  291. deallocate Diff
  292. if @DiffStructure = 1
  293. insert into #DiffStructure values (@PrevTName)
  294. '
  295. exec (@sqlStr)
  296. if (select count(*) from #DiffStructure) > 0
  297. begin
  298. print CHAR(10)+'The table(s) have the same name and different structure in the databases:'
  299. select distinct * from #DiffStructure
  300. delete from #TabToCheck where name in (select * from #DiffStructure)
  301. end
  302. else
  303. print CHAR(10)+'There are no tables with the same name and structural differences in the databases'+CHAR(10)+CHAR(10)
  304. if @OnlyStructure = 1
  305. begin
  306. print 'The option ''Only compare structures'' was specified. End of work.'
  307. return
  308. end
  309. exec ('declare @Name sysname select @Name=d1o.name
  310. from '+@db1+'.dbo.sysobjects d1o, '+@db2+'.dbo.sysobjects d2o
  311. where d1o.name = d2o.name and d1o.type = ''U'' and d2o.type = ''U''
  312. and d1o.name not in (''dtproperties'')
  313. and d1o.name in (select * from #TabToCheck)')
  314. if @@rowcount = 0
  315. begin
  316. print 'There are no tables with the same name and structure in the databases to compare. End of work.'
  317. return
  318. end
  319.  
  320.  
  321. -----------------------------------------------------------------------------------------
  322. -- Comparing data
  323. -----------------------------------------------------------------------------------------
  324. -- ##CompareStr - will be used to pass comparing strings into dynamic script
  325. -- to execute the string
  326. if exists (select * from tempdb.dbo.sysobjects where name like '##CompareStr%')
  327. drop table ##CompareStr
  328. create table ##CompareStr (Ind int, CompareStr varchar(8000))
  329.  
  330. if exists (select * from tempdb.dbo.sysobjects where name like '#DiffTables%')
  331. drop table #DiffTables
  332. create table #DiffTables (Name sysname)
  333. if exists (select * from tempdb.dbo.sysobjects where name like '#IdenticalTables%')
  334. drop table #IdenticalTables
  335. create table #IdenticalTables (Name sysname)
  336. if exists (select * from tempdb.dbo.sysobjects where name like '#EmptyTables%')
  337. drop table #EmptyTables
  338. create table #EmptyTables (Name sysname)
  339. if exists (select * from tempdb.dbo.sysobjects where name like '#NoPKTables%')
  340. drop table #NoPKTables
  341. create table #NoPKTables (Name sysname)
  342.  
  343. if exists (select * from tempdb.dbo.sysobjects where name like '#IndList1%')
  344. truncate table #IndList1
  345. else
  346. create table #IndList1 (IndId int, IndStatus int,
  347. KeyAndStr varchar(7000), KeyCommaStr varchar(1000))
  348. if exists (select * from tempdb.dbo.sysobjects where name like '#IndList2%')
  349. truncate table #IndList2
  350. else
  351. create table #IndList2 (IndId smallint, IndStatus int,
  352. KeyAndStr varchar(7000), KeyCommaStr varchar(1000))
  353.  
  354. print Replicate('-',51)
  355. print 'Comparing data in tables with indentical structure:'
  356. print Replicate('-',51)
  357. --------------------------------------------------------------------------------------------
  358. -- Cursor for all tables in dbs (or for all specified tables if parameter @TabList is passed)
  359. --------------------------------------------------------------------------------------------
  360. declare @SqlStrGetListOfKeys1 varchar(8000)
  361. declare @SqlStrGetListOfKeys2 varchar(8000)
  362. declare @SqlStrGetListOfColumns varchar(8000)
  363. declare @SqlStrCompareUKeyTables varchar(8000)
  364. declare @SqlStrCompareNonUKeyTables varchar(8000)
  365. set @SqlStrGetListOfKeys1 = '
  366. declare @sqlStr varchar(8000)
  367. declare @ExecSqlStr varchar(8000)
  368. declare @PrintSqlStr varchar(8000)
  369. declare @Tab varchar(128)
  370. declare @d1User varchar(128)
  371. declare @d2User varchar(128)
  372. declare @KeyAndStr varchar(8000)
  373. declare @KeyCommaStr varchar(8000)
  374. declare @AndStr varchar(8000)
  375. declare @Eq varchar(8000)
  376. declare @IndId int
  377. declare @IndStatus int
  378. declare @CurrIndId smallint
  379. declare @CurrStatus int
  380. declare @UKey sysname
  381. declare @Col varchar(128)
  382. declare @LastUsedCol varchar(128)
  383. declare @xType int
  384. declare @Len int
  385. declare @SelectStr varchar(8000)
  386. declare @ExecSql nvarchar(1000)
  387. declare @NotInDB1 bit
  388. declare @NotInDB2 bit
  389. declare @NotEq bit
  390. declare @Numb int
  391. declare @Cnt1 int
  392. declare @Cnt2 int
  393. set @Numb = 0
  394.  
  395. declare @StrInd int
  396. declare @i int
  397. declare @PrintStr varchar(8000)
  398. declare @ExecStr varchar(8000)
  399. declare TabCur cursor for
  400.  
  401. select d1o.name, d1u.name, d2u.name from '+@db1+'.dbo.sysobjects d1o, '+@db2+'.dbo.sysobjects d2o,
  402. '+@db1+'.dbo.sysusers d1u, '+@db2+'.dbo.sysusers d2u
  403. where d1o.name = d2o.name and d1o.type = ''U'' and d2o.type = ''U''
  404. and d1o.uid = d1u.uid and d2o.uid = d2u.uid
  405. and d1o.name not in (''dtproperties'')
  406. and d1o.name in (select * from #TabToCheck)
  407. order by 1
  408.  
  409. open TabCur
  410. fetch next from TabCur into @Tab, @d1User, @d2User
  411. while @@fetch_status = 0
  412. begin
  413. set @Numb = @Numb + 1
  414. print Char(13)+Char(10)+LTRIM(STR(@Numb))+''. TABLE: [''+@Tab+''] ''
  415.  
  416. set @ExecSql = ''SELECT @Cnt = count(*) FROM '+@db1+'.[''+@d1User+''].[''+@Tab+'']''
  417. exec sp_executesql @ExecSql, N''@Cnt int output'', @Cnt = @Cnt1 output
  418. print CHAR(10)+STR(@Cnt1)+'' rows in '+@db1+'''
  419. set @ExecSql = ''SELECT @Cnt = count(*) FROM '+@db2+'.[''+@d2User+''].[''+@Tab+'']''
  420. exec sp_executesql @ExecSql, N''@Cnt int output'', @Cnt = @Cnt2 output
  421. print STR(@Cnt2)+'' rows in '+@db2+'''
  422. if @Cnt1 = 0 and @Cnt2 = 0
  423. begin
  424. exec ('' insert into #EmptyTables values(''''[''+@Tab+'']'''')'')
  425. goto NextTab
  426. end
  427. set @KeyAndStr = ''''
  428. set @KeyCommaStr = ''''
  429. set @NotInDB1 = 0
  430. set @NotInDB2 = 0
  431. set @NotEq = 0
  432. set @KeyAndStr = ''''
  433. set @KeyCommaStr = ''''
  434. truncate table #IndList1
  435. declare UKeys cursor fast_forward for
  436. select i.indid, i.status, c.name, c.xType from '+@db1+'.dbo.sysobjects o, '+@db1+'.dbo.sysindexes i, '+@db1+'.dbo.sysindexkeys k, '+@db1+'.dbo.syscolumns c
  437. where i.id = o.id and o.name = @Tab
  438. and (i.status & 2)<>0
  439. and k.id = o.id and k.indid = i.indid
  440. and c.id = o.id and c.colid = k.colid
  441. order by i.indid, c.name
  442. open UKeys
  443. fetch next from UKeys into @IndId, @IndStatus, @UKey, @xType
  444. set @CurrIndId = @IndId
  445. set @CurrStatus = @IndStatus
  446. while @@fetch_status = 0
  447. begin
  448. if @KeyAndStr <> ''''
  449. begin
  450. set @KeyAndStr = @KeyAndStr + '' and '' + CHAR(10)
  451. set @KeyCommaStr = @KeyCommaStr + '', ''
  452. end
  453. if @xType = 175 or @xType = 167 or @xType = 239 or @xType = 231 -- char, varchar, nchar, nvarchar
  454. begin
  455. set @KeyAndStr = @KeyAndStr + '' ISNULL(d1.[''+@UKey+''],''''!#null$'''')=ISNULL(d2.[''+@UKey+''],''''!#null$'''') ''
  456. end
  457. if @xType = 173 or @xType = 165 -- binary, varbinary
  458. begin
  459. set @KeyAndStr = @KeyAndStr +
  460. '' CASE WHEN d1.[''+@UKey+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d1.[''+@UKey+''] END=''+
  461. ''CASE WHEN d2.[''+@UKey+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d2.[''+@UKey+''] END ''
  462. end
  463. else if @xType = 56 or @xType = 127 or @xType = 60 or @xType = 122 -- int, 127 - bigint,60 - money, 122 - smallmoney
  464. begin
  465. set @KeyAndStr = @KeyAndStr +
  466. '' CASE WHEN d1.[''+@UKey+''] is null THEN 971428763405345098745 ELSE d1.[''+@UKey+''] END=''+
  467. ''CASE WHEN d2.[''+@UKey+''] is null THEN 971428763405345098745 ELSE d2.[''+@UKey+''] END ''
  468. end
  469. else if @xType = 106 or @xType = 108 -- int, decimal, numeric
  470. begin
  471. set @KeyAndStr = @KeyAndStr +
  472. '' CASE WHEN d1.[''+@UKey+''] is null THEN 71428763405345098745098.8723 ELSE d1.[''+@UKey+''] END=''+
  473. ''CASE WHEN d2.[''+@UKey+''] is null THEN 71428763405345098745098.8723 ELSE d2.[''+@UKey+''] END ''
  474. end
  475. else if @xType = 62 or @xType = 59 -- 62 - float, 59 - real
  476. begin
  477. set @KeyAndStr = @KeyAndStr +
  478. '' CASE WHEN d1.[''+@UKey+''] is null THEN 8764589764.22708E237 ELSE d1.[''+@UKey+''] END=''+
  479. ''CASE WHEN d2.[''+@UKey+''] is null THEN 8764589764.22708E237 ELSE d2.[''+@UKey+''] END ''
  480. end
  481. else if @xType = 52 or @xType = 48 or @xType = 104 -- smallint, tinyint, bit
  482. begin
  483. set @KeyAndStr = @KeyAndStr + '' CASE WHEN d1.[''+@UKey+''] is null THEN 99999 ELSE d1.[''+@UKey+''] END=''+
  484. ''CASE WHEN d2.[''+@UKey+''] is null THEN 99999 ELSE d2.[''+@UKey+''] END ''
  485. end
  486. else if @xType = 36 -- 36 - id
  487. begin
  488. set @KeyAndStr = @KeyAndStr +
  489. '' CASE WHEN d1.[''+@UKey+''] is null''+
  490. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  491. '' ELSE d1.[''+@UKey+''] END=''+
  492. ''CASE WHEN d2.[''+@UKey+''] is null''+
  493. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  494. '' ELSE d2.[''+@UKey+''] END''
  495. end
  496. else if @xType = 61 or @xType = 58 -- datetime, smalldatetime
  497. begin
  498. set @KeyAndStr = @KeyAndStr +
  499. '' CASE WHEN d1.[''+@UKey+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d1.[''+@UKey+''],109) END=''+
  500. ''CASE WHEN d2.[''+@UKey+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d2.[''+@UKey+''],109) END ''
  501. end
  502. else if @xType = 189 -- timestamp (189)
  503. begin
  504. set @KeyAndStr = @KeyAndStr + '' d1.[''+@UKey+'']=d2.[''+@UKey+''] ''
  505. end
  506. else if @xType = 98 -- SQL_variant
  507. begin
  508. set @KeyAndStr = @KeyAndStr + '' ISNULL(d1.[''+@UKey+''],''''!#null$'''')=ISNULL(d2.[''+@UKey+''],''''!#null$'''') ''
  509. end
  510. set @KeyCommaStr = @KeyCommaStr + '' d1.''+@UKey
  511. fetch next from UKeys into @IndId, @IndStatus, @UKey, @xType
  512. if @IndId <> @CurrIndId
  513. begin
  514. insert into #IndList1 values (@CurrIndId, @CurrStatus, @KeyAndStr, @KeyCommaStr)
  515. set @CurrIndId = @IndId
  516. set @CurrStatus = @IndStatus
  517. set @KeyAndStr = ''''
  518. set @KeyCommaStr = ''''
  519. end
  520. end
  521. deallocate UKeys
  522. insert into #IndList1 values (@CurrIndId, @CurrStatus, @KeyAndStr, @KeyCommaStr)'
  523. set @SqlStrGetListOfKeys2 = '
  524. set @KeyAndStr = ''''
  525. set @KeyCommaStr = ''''
  526. truncate table #IndList2
  527. declare UKeys cursor fast_forward for
  528. select i.indid, i.status, c.name, c.xType from '+@db2+'.dbo.sysobjects o, '+@db2+'.dbo.sysindexes i, '+@db2+'.dbo.sysindexkeys k, '+@db2+'.dbo.syscolumns c
  529. where i.id = o.id and o.name = @Tab
  530. and (i.status & 2)<>0
  531. and k.id = o.id and k.indid = i.indid
  532. and c.id = o.id and c.colid = k.colid
  533. order by i.indid, c.name
  534. open UKeys
  535. fetch next from UKeys into @IndId, @IndStatus, @UKey, @xType
  536. set @CurrIndId = @IndId
  537. set @CurrStatus = @IndStatus
  538. while @@fetch_status = 0
  539. begin
  540. if @KeyAndStr <> ''''
  541. begin
  542. set @KeyAndStr = @KeyAndStr + '' and '' + CHAR(10)
  543. set @KeyCommaStr = @KeyCommaStr + '', ''
  544. end
  545. if @xType = 175 or @xType = 167 or @xType = 239 or @xType = 231 -- char, varchar, nchar, nvarchar
  546. begin
  547. set @KeyAndStr = @KeyAndStr + '' ISNULL(d1.[''+@UKey+''],''''!#null$'''')=ISNULL(d2.[''+@UKey+''],''''!#null$'''') ''
  548. end
  549. if @xType = 173 or @xType = 165 -- binary, varbinary
  550. begin
  551. set @KeyAndStr = @KeyAndStr +
  552. '' CASE WHEN d1.[''+@UKey+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d1.[''+@UKey+''] END=''+
  553. ''CASE WHEN d2.[''+@UKey+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d2.[''+@UKey+''] END ''
  554. end
  555. else if @xType = 56 or @xType = 127 or @xType = 60 or @xType = 122 -- int, 127 - bigint,60 - money, 122 - smallmoney
  556. begin
  557. set @KeyAndStr = @KeyAndStr +
  558. '' CASE WHEN d1.[''+@UKey+''] is null THEN 971428763405345098745 ELSE d1.[''+@UKey+''] END=''+
  559. ''CASE WHEN d2.[''+@UKey+''] is null THEN 971428763405345098745 ELSE d2.[''+@UKey+''] END ''
  560. end
  561. else if @xType = 106 or @xType = 108 -- int, decimal, numeric
  562. begin
  563. set @KeyAndStr = @KeyAndStr +
  564. '' CASE WHEN d1.[''+@UKey+''] is null THEN 71428763405345098745098.8723 ELSE d1.[''+@UKey+''] END=''+
  565. ''CASE WHEN d2.[''+@UKey+''] is null THEN 71428763405345098745098.8723 ELSE d2.[''+@UKey+''] END ''
  566. end
  567. else if @xType = 62 or @xType = 59 -- 62 - float, 59 - real
  568. begin
  569. set @KeyAndStr = @KeyAndStr +
  570. '' CASE WHEN d1.[''+@UKey+''] is null THEN 8764589764.22708E237 ELSE d1.[''+@UKey+''] END=''+
  571. ''CASE WHEN d2.[''+@UKey+''] is null THEN 8764589764.22708E237 ELSE d2.[''+@UKey+''] END ''
  572. end
  573. else if @xType = 52 or @xType = 48 or @xType = 104 -- smallint, tinyint, bit
  574. begin
  575. set @KeyAndStr = @KeyAndStr + '' CASE WHEN d1.[''+@UKey+''] is null THEN 99999 ELSE d1.[''+@UKey+''] END=''+
  576. ''CASE WHEN d2.[''+@UKey+''] is null THEN 99999 ELSE d2.[''+@UKey+''] END ''
  577. end
  578. else if @xType = 36 -- 36 - id
  579. begin
  580. set @KeyAndStr = @KeyAndStr +
  581. '' CASE WHEN d1.[''+@UKey+''] is null''+
  582. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  583. '' ELSE d1.[''+@UKey+''] END=''+
  584. ''CASE WHEN d2.[''+@UKey+''] is null''+
  585. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  586. '' ELSE d2.[''+@UKey+''] END''
  587. end
  588. else if @xType = 61 or @xType = 58 -- datetime, smalldatetime
  589. begin
  590. set @KeyAndStr = @KeyAndStr +
  591. '' CASE WHEN d1.[''+@UKey+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d1.[''+@UKey+''],109) END=''+
  592. ''CASE WHEN d2.[''+@UKey+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d2.[''+@UKey+''],109) END ''
  593. end
  594. else if @xType = 189 -- timestamp (189)
  595. begin
  596. set @KeyAndStr = @KeyAndStr + '' d1.[''+@UKey+'']=d2.[''+@UKey+''] ''
  597. end
  598. else if @xType = 98 -- SQL_variant
  599. begin
  600. set @KeyAndStr = @KeyAndStr + '' ISNULL(d1.[''+@UKey+''],''''!#null$'''')=ISNULL(d2.[''+@UKey+''],''''!#null$'''') ''
  601. end
  602. set @KeyCommaStr = @KeyCommaStr + '' d1.''+@UKey
  603. fetch next from UKeys into @IndId, @IndStatus, @UKey, @xType
  604. if @IndId <> @CurrIndId
  605. begin
  606. insert into #IndList2 values (@CurrIndId, @CurrStatus, @KeyAndStr, @KeyCommaStr)
  607. set @CurrIndId = @IndId
  608. set @CurrStatus = @IndStatus
  609. set @KeyAndStr = ''''
  610. set @KeyCommaStr = ''''
  611. end
  612. end
  613. deallocate UKeys
  614. insert into #IndList2 values (@CurrIndId, @CurrStatus, @KeyAndStr, @KeyCommaStr)
  615. set @KeyCommaStr = null
  616.  
  617. select @KeyCommaStr=i1.KeyCommaStr from #IndList1 i1
  618. join #IndList2 i2 on i1.KeyCommaStr = i2.KeyCommaStr
  619. where (i1.IndStatus & 2048)<> 0 and (i2.IndStatus & 2048)<>0
  620.  
  621. if @KeyCommaStr is null
  622. set @KeyCommaStr = (select top 1 i1.KeyCommaStr from #IndList1 i1
  623. join #IndList2 i2 on i1.KeyCommaStr = i2.KeyCommaStr)
  624. set @KeyAndStr = (select TOP 1 KeyAndStr from #IndList1 where KeyCommaStr = @KeyCommaStr)
  625. if @KeyCommaStr is null
  626. set @KeyCommaStr = ''''
  627. if @KeyAndStr is null
  628. set @KeyAndStr = '''''
  629. set @SqlStrGetListOfColumns = '
  630. set @AndStr = ''''
  631. set @StrInd = 1
  632. declare Cols cursor local fast_forward for
  633. select c.name, c.xtype, c.length from '+@db1+'.dbo.sysobjects o, '+@db1+'.dbo.syscolumns c
  634. where o.id = c.id and o.name = @Tab
  635. and CHARINDEX(c.name, @KeyCommaStr) = 0
  636. open Cols
  637. fetch next from Cols into @Col, @xType, @len
  638. while @@fetch_status = 0
  639. begin
  640. if @xType = 175 or @xType = 167 or @xType = 239 or @xType = 231 -- char, varchar, nchar, nvarchar
  641. begin
  642. set @Eq = ''ISNULL(d1.[''+@Col+''],''''!#null$'''')=ISNULL(d2.[''+@Col+''],''''!#null$'''') ''
  643. end
  644. if @xType = 173 or @xType = 165 -- binary, varbinary
  645. begin
  646. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d1.[''+@Col+''] END=''+
  647. ''CASE WHEN d2.[''+@Col+''] is null THEN 0x4D4FFB23A49411D5BDDB00A0C906B7B4 ELSE d2.[''+@Col+''] END ''
  648. end
  649. else if @xType = 56 or @xType = 127 or @xType = 60 or @xType = 122 -- int, 127 - bigint,60 - money, 122 - smallmoney
  650. begin
  651. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null THEN 971428763405345098745 ELSE d1.[''+@Col+''] END=''+
  652. ''CASE WHEN d2.[''+@Col+''] is null THEN 971428763405345098745 ELSE d2.[''+@Col+''] END ''
  653. end
  654. else if @xType = 106 or @xType = 108 -- int, decimal, numeric
  655. begin
  656. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null THEN 71428763405345098745098.8723 ELSE d1.[''+@Col+''] END=''+
  657. ''CASE WHEN d2.[''+@Col+''] is null THEN 71428763405345098745098.8723 ELSE d2.[''+@Col+''] END ''
  658. end
  659. else if @xType = 62 or @xType = 59 -- 62 - float, 59 - real
  660. begin
  661. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null THEN 8764589764.22708E237 ELSE d1.[''+@Col+''] END=''+
  662. ''CASE WHEN d2.[''+@Col+''] is null THEN 8764589764.22708E237 ELSE d2.[''+@Col+''] END ''
  663. end
  664. else if @xType = 52 or @xType = 48 or @xType = 104 -- smallint, tinyint, bit
  665. begin
  666. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null THEN 99999 ELSE d1.[''+@Col+''] END=''+
  667. ''CASE WHEN d2.[''+@Col+''] is null THEN 99999 ELSE d2.[''+@Col+''] END ''
  668. end
  669. else if @xType = 36 -- 36 - id
  670. begin
  671. set @Eq = ''CASE WHEN d1.[''+@Col+''] is null''+
  672. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  673. '' ELSE d1.[''+@Col+''] END=''+
  674. ''CASE WHEN d2.[''+@Col+''] is null''+
  675. '' THEN CONVERT(uniqueidentifier,''''1CD827A0-744A-4866-8401-B9902CF2D4FB'''')''+
  676. '' ELSE d2.[''+@Col+''] END''
  677. end
  678. else if @xType = 61 or @xType = 58 -- datetime, smalldatetime
  679. begin
  680. set @Eq =
  681. ''CASE WHEN d1.[''+@Col+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d1.[''+@Col+''],109) END=''+
  682. ''CASE WHEN d2.[''+@Col+''] is null THEN ''''!#null$'''' ELSE CONVERT(varchar(40),d2.[''+@Col+''],109) END ''
  683. end
  684. else if @xType = 34
  685. begin
  686. set @Eq = ''ISNULL(DATALENGTH(d1.[''+@Col+'']),0)=ISNULL(DATALENGTH(d2.[''+@Col+'']),0) ''
  687. end
  688. else if @xType = 35 or @xType = 99 -- text (35),ntext (99)
  689. begin
  690. set @Eq = ''ISNULL(SUBSTRING(d1.[''+@Col+''],1,DATALENGTH(d1.[''+@Col+
  691. ''])),''''!#null$'''')=ISNULL(SUBSTRING(d2.[''+@Col+''],1,DATALENGTH(d2.[''+@Col+''])),''''!#null$'''') ''
  692. end
  693. else if @xType = 189
  694. begin
  695. if '+STR(@NoTimestamp)+' = 0
  696. set @Eq = ''d1.[''+@Col+'']=d2.[''+@Col+''] ''
  697. else
  698. set @Eq = ''1=1''
  699. end
  700. else if @xType = 98 -- SQL_variant
  701. begin
  702. set @Eq = ''ISNULL(d1.[''+@Col+''],''''!#null$'''')=ISNULL(d2.[''+@Col+''],''''!#null$'''') ''
  703. end
  704. if @AndStr = ''''
  705. set @AndStr = @AndStr + CHAR(10) + '' '' + @Eq
  706. else
  707. if len(@AndStr) + len('' and '' + @Eq)<8000
  708. set @AndStr = @AndStr + '' and '' + CHAR(10) + '' '' + @Eq
  709. else
  710. begin
  711. set @StrInd = @StrInd + 1
  712. Insert into ##CompareStr values(@StrInd,@AndStr)
  713. set @AndStr = '' and '' + @Eq
  714. end
  715. fetch next from Cols into @Col, @xType, @len
  716. end
  717. deallocate Cols '
  718. set @SqlStrCompareUKeyTables = '
  719. if @KeyAndStr <> ''''
  720. begin
  721. set @SelectStr = ''SELECT ''+ @KeyCommaStr+'' INTO ##NotInDb2 FROM '+@db1+'.[''+@d1User+''].[''+@Tab+''] d1 ''+
  722. '' WHERE not exists''+CHAR(10)+'' (SELECT * FROM '+@db2+'.[''+@d2User+''].[''+@Tab+''] d2 ''+
  723. '' WHERE ''+CHAR(10)+@KeyAndStr+'')''
  724. if '+STR(@VerboseLevel)+' = 1
  725. print CHAR(10)+''To find rows that are in '+@db1+', but are not in db2:''+CHAR(10)+
  726. REPLACE (@SelectStr, ''into ##NotInDB2'','''')
  727. exec (@SelectStr)
  728. if @@rowcount > 0
  729. set @NotInDB2 = 1
  730. set @SelectStr = ''SELECT ''+@KeyCommaStr+'' INTO ##NotInDB1 FROM '+@db2+'.[''+@d2User+''].[''+@Tab+''] d1 ''+
  731. '' WHERE not exists''+CHAR(10)+'' (SELECT * FROM '+@db1+'.[''+@d1User+''].[''+@Tab+''] d2 ''+
  732. '' WHERE ''+CHAR(10)+@KeyAndStr+'')''
  733. if '+STR(@VerboseLevel)+' = 1
  734. print CHAR(10)+''To find rows that are in '+@db2+', but are not in '+@db1+':''+CHAR(10)+
  735. REPLACE (@SelectStr, ''into ##NotInDB1'','''')
  736. exec (@SelectStr)
  737. if @@rowcount > 0
  738. set @NotInDB1 = 1
  739. -- if there are non-key columns
  740. if @AndStr <> ''''
  741. begin
  742. set @PrintStr = '' Print ''
  743. set @ExecStr = '' exec (''
  744. set @SqlStr = ''''
  745. Insert into ##CompareStr values(1,
  746. ''SELECT ''+ @KeyCommaStr+'' INTO ##NotEq FROM '+@db2+'.[''+@d2User+''].[''+@Tab+''] d1 ''+
  747. '' INNER JOIN '+@db1+'.[''+@d1User+''].[''+@Tab+''] d2 ON ''+CHAR(10)+@KeyAndStr+CHAR(10)+''WHERE not('')
  748. -- Adding last string in temp table containing a comparing string to execute
  749. set @StrInd = @StrInd + 1
  750. Insert into ##CompareStr values(@StrInd,@AndStr+'')'')
  751. set @i = 1
  752. while @i <= @StrInd
  753. begin
  754. set @SqlStr = @SqlStr + '' declare @Str''+LTRIM(STR(@i))+'' varchar(8000) ''+
  755. ''select @Str''+LTRIM(STR(@i))+''=CompareStr FROM ##CompareStr WHERE ind = ''+STR(@i)
  756. if @ExecStr <> '' exec (''
  757. set @ExecStr = @ExecStr + ''+''
  758. if @PrintStr <> '' Print ''
  759. set @PrintStr = @PrintStr + ''+''
  760. set @ExecStr = @ExecStr + ''@Str''+LTRIM(STR(@i))
  761. set @PrintStr = @PrintStr + '' REPLACE(@Str''+LTRIM(STR(@i))+'','''' into ##NotEq'''','''''''') ''
  762. set @i = @i + 1
  763. end
  764. set @ExecStr = @ExecStr + '') ''
  765. set @ExecSqlStr = @SqlStr + @ExecStr
  766. set @PrintSqlStr = @SqlStr +
  767. '' Print CHAR(10)+''''To find rows that are different in non-key columns:'''' ''+
  768. @PrintStr
  769. if '+STR(@VerboseLevel)+' = 1
  770. exec (@PrintSqlStr)
  771. exec (@ExecSqlStr)
  772.  
  773. if @@rowcount > 0
  774. set @NotEq = 1
  775. end
  776. else
  777. if '+STR(@VerboseLevel)+' = 1
  778. print CHAR(10)+''There are no non-key columns in the table''
  779. truncate table ##CompareStr
  780. if @NotInDB1 = 1 or @NotInDB2 = 1 or @NotEq = 1
  781. begin
  782. print CHAR(10)+''Data are different''
  783. if @NotInDB2 = 1 and '+STR(@NumbToShow)+' > 0
  784. begin
  785. print ''These key values exist in '+@db1+', but do not exist in '+@db2+': ''
  786. set @SelectStr = ''select top ''+STR('+STR(@NumbToShow)+')+'' * from ##NotInDB2''
  787. exec (@SelectStr)
  788. end
  789. if @NotInDB1 = 1 and '+STR(@NumbToShow)+' > 0
  790. begin
  791. print ''These key values exist in '+@db2+', but do not exist in '+@db1+': ''
  792. set @SelectStr = ''select top ''+STR('+STR(@NumbToShow)+')+'' * from ##NotInDB1''
  793. exec (@SelectStr)
  794. end
  795. if @NotEq = 1 and '+STR(@NumbToShow)+' > 0
  796. begin
  797. print ''Row(s) with these key values contain differences in non-key columns: ''
  798. set @SelectStr = ''select top ''+STR('+STR(@NumbToShow)+')+'' * from ##NotEq''
  799. exec (@SelectStr)
  800. end
  801. exec (''insert into #DiffTables values(''''[''+@Tab+'']'''')'')
  802. end
  803. else
  804. begin
  805. print CHAR(10)+''Data are identical''
  806. exec ('' insert into #IdenticalTables values(''''[''+@Tab+'']'''')'')
  807. end
  808. if exists (select * from tempdb.dbo.sysobjects where name like ''##NotEq%'')
  809. drop table ##NotEq
  810. end
  811. else '
  812. set @SqlStrCompareNonUKeyTables = '
  813. begin
  814. exec (''insert into #NoPKTables values(''''[''+@Tab+'']'''')'')
  815. set @PrintStr = '' Print ''
  816. set @ExecStr = '' exec (''
  817. set @SqlStr = ''''
  818. Insert into ##CompareStr values(1,
  819. ''SELECT ''+
  820. '' * INTO ##NotInDB2 FROM '+@db1+'.[''+@d1User+''].[''+@Tab+''] d1 WHERE not exists ''+CHAR(10)+
  821. '' (SELECT * FROM '+@db2+'.[''+@d2User+''].[''+@Tab+''] d2 WHERE '')
  822. set @StrInd = @StrInd + 1
  823. Insert into ##CompareStr values(@StrInd,@AndStr+'')'')
  824. set @i = 1
  825. while @i <= @StrInd
  826. begin
  827. set @SqlStr = @SqlStr + '' declare @Str''+LTRIM(STR(@i))+'' varchar(8000) ''+
  828. ''select @Str''+LTRIM(STR(@i))+''=CompareStr FROM ##CompareStr WHERE ind = ''+STR(@i)
  829. if @ExecStr <> '' exec (''
  830. set @ExecStr = @ExecStr + ''+''
  831. if @PrintStr <> '' Print ''
  832. set @PrintStr = @PrintStr + ''+''
  833. set @ExecStr = @ExecStr + ''@Str''+LTRIM(STR(@i))
  834. set @PrintStr = @PrintStr + '' REPLACE(@Str''+LTRIM(STR(@i))+'','''' into ##NotInDB2'''','''''''') ''
  835. set @i = @i + 1
  836. end
  837. set @ExecStr = @ExecStr + '') ''
  838. set @ExecSqlStr = @SqlStr + @ExecStr
  839. set @PrintSqlStr = @SqlStr +
  840. '' Print CHAR(10)+''''To find rows that are in '+@db1+', but are not in '+@db2+':'''' ''+
  841. @PrintStr
  842. if '+STR(@VerboseLevel)+' = 1
  843. exec (@PrintSqlStr)
  844. exec (@ExecSqlStr)
  845.  
  846. if @@rowcount > 0
  847. set @NotInDB2 = 1
  848. delete from ##CompareStr where ind = 1
  849. set @PrintStr = '' Print ''
  850. set @ExecStr = '' exec (''
  851. set @SqlStr = ''''
  852. Insert into ##CompareStr values(1,
  853. ''SELECT ''+
  854. '' * INTO ##NotInDB1 FROM '+@db2+'.[''+@d2User+''].[''+@Tab+''] d1 WHERE not exists ''+CHAR(10)+
  855. '' (SELECT * FROM '+@db1+'.[''+@d1User+''].[''+@Tab+''] d2 WHERE '')
  856. set @i = 1
  857. while @i <= @StrInd
  858. begin
  859. set @SqlStr = @SqlStr + '' declare @Str''+LTRIM(STR(@i))+'' varchar(8000) ''+
  860. ''select @Str''+LTRIM(STR(@i))+''=CompareStr FROM ##CompareStr WHERE ind = ''+STR(@i)
  861. if @ExecStr <> '' exec (''
  862. set @ExecStr = @ExecStr + ''+''
  863. if @PrintStr <> '' Print ''
  864. set @PrintStr = @PrintStr + ''+''
  865. set @ExecStr = @ExecStr + ''@Str''+LTRIM(STR(@i))
  866. set @PrintStr = @PrintStr + '' REPLACE(@Str''+LTRIM(STR(@i))+'','''' into ##NotInDB1'''','''''''') ''
  867. set @i = @i + 1
  868. end
  869. set @ExecStr = @ExecStr + '') ''
  870. set @ExecSqlStr = @SqlStr + @ExecStr
  871. set @PrintSqlStr = @SqlStr +
  872. '' Print CHAR(10)+''''To find rows that are in '+@db2+', but are not in '+@db1+':'''' ''+
  873. @PrintStr
  874. if '+STR(@VerboseLevel)+' = 1
  875. exec (@PrintSqlStr)
  876. exec (@ExecSqlStr)
  877.  
  878. if @@rowcount > 0
  879. set @NotInDB1 = 1
  880. truncate table ##CompareStr
  881. if @NotInDB1 = 1 or @NotInDB2 = 1
  882. begin
  883. print CHAR(10)+''Data are different''
  884. if @NotInDB2 = 1 and '+STR(@NumbToShow)+' > 0
  885. begin
  886. print ''The row(s) exist in '+@db1+', but do not exist in '+@db2+': ''
  887. set @SelectStr = ''select top ''+STR('+STR(@NumbToShow)+')+'' * from ##NotInDB2''
  888. exec (@SelectStr)
  889. end
  890. if @NotInDB1 = 1 and '+STR(@NumbToShow)+' > 0
  891. begin
  892. print ''The row(s) exist in '+@db2+', but do not exist in '+@db1+': ''
  893. set @SelectStr = ''select top ''+STR('+STR(@NumbToShow)+')+'' * from ##NotInDB1''
  894. exec (@SelectStr)
  895. end
  896. exec (''insert into #DiffTables values(''''[''+@Tab+'']'''')'')
  897. end
  898. else
  899. begin
  900. print CHAR(10)+''Data are identical''
  901. exec ('' insert into #IdenticalTables values(''''[''+@Tab+'']'''')'')
  902. end
  903. end
  904. if exists (select * from tempdb.dbo.sysobjects where name like ''##NotInDB1%'')
  905. drop table ##NotInDB1
  906. if exists (select * from tempdb.dbo.sysobjects where name like ''##NotInDB2%'')
  907. drop table ##NotInDB2
  908. NextTab:
  909. fetch next from TabCur into @Tab, @d1User, @d2User
  910. end
  911. deallocate TabCur
  912. '
  913. exec (@SqlStrGetListOfKeys1+@SqlStrGetListOfKeys2+@SqlStrGetListOfColumns+
  914. @SqlStrCompareUKeyTables+@SqlStrCompareNonUKeyTables)
  915. print ' '
  916. SET NOCOUNT OFF
  917. if (select count(*) from #NoPKTables) > 0
  918. begin
  919. select name as 'Table(s) without Unique key:' from #NoPKTables
  920. end
  921. if (select count(*) from #DiffTables) > 0
  922. begin
  923. select name as 'Table(s) with the same name & structure, but different data:' from #DiffTables
  924. end
  925. else
  926. print CHAR(10)+'No tables with the same name & structure, but different data'+CHAR(10)
  927. if (select count(*) from #IdenticalTables) > 0
  928. begin
  929. select name as 'Table(s) with the same name & structure and identical data:' from #IdenticalTables
  930. end
  931. if (select count(*) from #EmptyTables) > 0
  932. begin
  933. select name as 'Table(s) with the same name & structure and empty in the both databases:' from #EmptyTables
  934. end
  935. drop table #TabToCheck
  936. drop table ##CompareStr
  937. drop table #DiffTables
  938. drop table #IdenticalTables
  939. drop table #EmptyTables
  940. drop table #NoPKTables
  941. drop table #IndList1
  942. drop table #IndList2
  943. return
  944.  
  945.  
  946.  

 :kicking:  espero les sirva
 :comp:
"Somos lo que imaginamos ser"
-- --------------------------------------------------------------
-ElNapster
-Designer / Developer Software
-GuaTemALa



Soultaker

  • Miembro HIPER activo
  • ****
  • Mensajes: 972
  • Nacionalidad: pe
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #5 en: Jueves 26 de Octubre de 2006, 00:56 »
0
tan pequeño es el codigo.  :(  :(

 :comp:
http]
foros,programacion, c, c++, java,
linux, videojuegos, directX, .NET,
visual basic,robotica,microprocesadores

Para los nuevos usuarios de este Foro, por favor leerse esta discusión.
Cómo Hacer Preguntas De Forma Inteligente

Ojos que no ven... pisan caquita
Camarón que se duerme... muere electrocutado


<<< Harol Moreyra Bendezú >>>

JuanK

  • Miembro de ORO
  • ******
  • Mensajes: 5393
  • Nacionalidad: co
    • Ver Perfil
    • http://juank.io
Re: Comparacion De Campos
« Respuesta #6 en: Jueves 26 de Octubre de 2006, 01:01 »
0
Me parece un script muy inutil, apuesto a que se puede hacer uno mas corto aprovechando mejor el diccionario de datos de la base de datos... :whistling:

A no ser claro que SQlServer tenga un diccionario de datos muy malo.  :scream:
[size=109]Juan Carlos Ruiz Pacheco
[/size]
Microsoft Technical Evangelist
@JuanKRuiz
http://juank.io

ElNapster

  • Moderador
  • ******
  • Mensajes: 727
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #7 en: Jueves 26 de Octubre de 2006, 01:15 »
0
Eso parece , pero fue lo que pude encontrar, tras unas cuantas horas en el internet   :comp:  , y les cuento que ni lo he utilizado  :P , porque como dice JuanK se ve un scrip muy inutil , aunque aca en el trabajo utilizo el sql 2000, talvez el 2005 ya tenga algo como dice Juank de lo del db link (en oracle) , pero no he revisado en casa si lo tiene  &lt;_&lt;, por el momento ya no me importa jajajaja :lol:
"Somos lo que imaginamos ser"
-- --------------------------------------------------------------
-ElNapster
-Designer / Developer Software
-GuaTemALa



lencho

  • Miembro de PLATA
  • *****
  • Mensajes: 1076
    • Ver Perfil
Re: Comparacion De Campos
« Respuesta #8 en: Jueves 26 de Octubre de 2006, 06:36 »
0
Es verdad el code esta bastante grande y muy complejo por lo que vi.

Habra que seguir buscando nomaj.

BYTE.
______________________________________________________________________________________
"No estoy de acuerdo con lo que dices, pero defenderé con mi vida tu derecho a expresarlo"

Mollense

  • Miembro de PLATA
  • *****
  • Mensajes: 1755
  • Nacionalidad: ar
    • Ver Perfil
    • http://solocodigo.com/
Re: Comparacion De Campos
« Respuesta #9 en: Jueves 26 de Octubre de 2006, 19:43 »
0
Puede ser una burrada lo que voy a decir pero...

¿No es posible crear dos conexiones una para cada DB, extraer los datos y luego crear una función que los compare?

Aunque el rendimiento sea pésimo creo que se podría hacer.

PD: No se enojen con mi ignorancia  :lol:
"Los que renuncian son más numerosos que los que fracasan" H.F.
"No se cómo sería la III Guerra Mundial, pero la cuarta sería con piedras" A.E.
"Quién no fía no es de fiar..."


...no te quedes mirando.

JuanK

  • Miembro de ORO
  • ******
  • Mensajes: 5393
  • Nacionalidad: co
    • Ver Perfil
    • http://juank.io
Re: Comparacion De Campos
« Respuesta #10 en: Jueves 26 de Octubre de 2006, 20:43 »
0
Funcionaria pero si es una burrada, no solo por el tiewmpo enorme que tomaria la comparacion de los objetos sino por el degaste en codificacion.
[size=109]Juan Carlos Ruiz Pacheco
[/size]
Microsoft Technical Evangelist
@JuanKRuiz
http://juank.io

Mollense

  • Miembro de PLATA
  • *****
  • Mensajes: 1755
  • Nacionalidad: ar
    • Ver Perfil
    • http://solocodigo.com/
Re: Comparacion De Campos
« Respuesta #11 en: Viernes 27 de Octubre de 2006, 03:04 »
0
Cita de: "JuanK"
Funcionaria pero si es una burrada
.
Bueno bueno he!

Una cosa es que lo diga yo y otra es que lo repitan.  :lightsabre:

Mentira, es broma.

Ya se que es una pésima solución pero una solución al fin.
"Los que renuncian son más numerosos que los que fracasan" H.F.
"No se cómo sería la III Guerra Mundial, pero la cuarta sería con piedras" A.E.
"Quién no fía no es de fiar..."


...no te quedes mirando.