Get Core SQLServer Health Metrics using Dynamic SQL
Recently, on his blog, Steve Jones invited the SQL community to write blog posts sharing their way of using SQL dynamically.
Accepting the invitation, in this blog, I am going to talk about how I am using Dynamic SQL to monitor the core health metrics of baselined SQL Server instances as part of the open-source monitoring tool SQLMonitor.
In SQLMonitor, on the central/inventory server, we have one view dbo.vw_all_server_info which is populated every 20 seconds with the core SQL Server metrics of each SQL Server instance we baseline. The job which takes care of this task is (dba) Get-AllServerInfo with the below 2-step codes –
1 2 3 4 5 6 7 |
-- Stable Info if ( (select count(1) from dbo.all_server_stable_info) <> (select count(distinct sql_instance) from dbo.instance_details) ) or ( (select max(collection_time) from dbo.all_server_stable_info) < dateadd(minute, -30, SYSDATETIME()) ) begin exec dbo.usp_GetAllServerInfo @result_to_table = 'dbo.all_server_stable_info', @output = 'srv_name, at_server_name, machine_name, server_name, ip, domain, host_name, product_version, edition, sqlserver_start_time_utc, total_physical_memory_kb, os_start_time_utc, cpu_count, scheduler_count, major_version_number, minor_version_number'; end |
1 2 3 |
-- Volatile Info exec dbo.usp_GetAllServerInfo @result_to_table = 'dbo.all_server_volatile_info', @output = 'srv_name, os_cpu, sql_cpu, pcnt_kernel_mode, page_faults_kb, blocked_counts, blocked_duration_max_seconds, available_physical_memory_kb, system_high_memory_signal_state, physical_memory_in_use_kb, memory_grants_pending, connection_count, active_requests_count, waits_per_core_per_minute'; |
If we look at the above 2 job step code blocks, we may guess by now, the base of this core SQL Server health metrics collection is stored procedure dbo.usp_GetAllServerInfo. Below is the result of the stored procedure in general when no parameters are used while calling –
To put it in simple terms, the stored procedure dbo.usp_GetAllServerInfo, when executed, connects to each SQL Server instance baselined with SQLMonitor, and gathers a total of 25-26 core health metrics in an efficient manner without burdening each server. Below are the key features/requirement of this procedure –
- Actively query specific servers, a list of servers, or all servers depending on the parameter values. Controlled by parameter @servers.
- Query specific health metrics like cpu cores, sql schedulers, % cpu utilization, memory grant pending etc depending on that what metrics are requested. Controlled by parameter @output.
- When a table name is passed in parameter @result_to_table, then create the table if not exists, and populate it with the required metrics for mentioned servers.
- Debug procedure with @verbose in the event of some bug/analysis requirement.
- The flexibility of adding more metrics collection easily without disrupting existing metric collection.
- Advanced enough to work in mixed environments where the inventory/central server and each server being baselined could be in different zones, domains, SQL Service Accounts, etc.
Let’s dig deeper into the code of dbo.usp_GetAllServerInfo in order to understand how we are utilizing Linked Server with Dynamic SQL to meet the above requirements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 |
IF APP_NAME() = 'Microsoft SQL Server Management Studio - Query' BEGIN SET QUOTED_IDENTIFIER OFF; SET ANSI_PADDING ON; SET CONCAT_NULL_YIELDS_NULL ON; SET ANSI_WARNINGS ON; SET NUMERIC_ROUNDABORT OFF; SET ARITHABORT ON; END GO IF DB_NAME() = 'master' raiserror ('Kindly execute all queries in [DBA] database', 20, -1) with log; go IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'usp_GetAllServerInfo') EXEC ('CREATE PROC dbo.usp_GetAllServerInfo AS SELECT ''stub version, to be replaced''') GO -- DROP PROCEDURE dbo.usp_GetAllServerInfo go ALTER PROCEDURE dbo.usp_GetAllServerInfo ( @servers varchar(max) = null, /* comma separated list of servers to query */ @blocked_threshold_seconds int = 60, @output nvarchar(max) = null, /* comma separated list of columns required in output */ @result_to_table nvarchar(125) = null, /* temp table that should be populated with result */ @verbose tinyint = 0 /* display debugging messages. 0 = No messages. 1 = Only print messages. 2 = Print & Table Results */ ) WITH EXECUTE AS OWNER --,RECOMPILE AS BEGIN /* Version: 1.0.2 Date: 2022-09-14 declare @srv_name varchar(125) = convert(varchar,serverproperty('MachineName')); exec dbo.usp_GetAllServerInfo @servers = @srv_name --exec dbo.usp_GetAllServerInfo @servers = 'Workstation,SqlPractice,SqlMonitor' ,@output = 'srv_name, os_start_time_utc' --exec dbo.usp_GetAllServerInfo @servers = 'SQLMONITOR' ,@output = 'system_high_memory_signal_state' https://stackoverflow.com/questions/10191193/how-to-test-linkedservers-connectivity-in-tsql exec dbo.usp_GetAllServerInfo @servers = 'SqlPractice' ,@output = 'memory_grants_pending' ,@verbose = 2 */ SET NOCOUNT ON; SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SET LOCK_TIMEOUT 60000; -- 60 seconds DECLARE @_tbl_servers table (srv_name varchar(125)); DECLARE @_tbl_output_columns table (column_name varchar(125)); DECLARE @_linked_server_failed bit = 0; DECLARE @_sql NVARCHAR(max); DECLARE @_isLocalHost bit = 0; create table #server_details ( srv_name varchar(125), at_server_name varchar(125), machine_name varchar(125), server_name varchar(125), ip varchar(30), domain varchar(125), host_name varchar(125), product_version varchar(30), edition varchar(50), sqlserver_start_time_utc datetime2, os_cpu decimal(20,2), sql_cpu decimal(20,2), pcnt_kernel_mode decimal(20,2), page_faults_kb decimal(20,2), blocked_counts int, blocked_duration_max_seconds bigint, total_physical_memory_kb bigint, available_physical_memory_kb bigint, system_high_memory_signal_state varchar(20), physical_memory_in_use_kb decimal(20,2), memory_grants_pending int, connection_count int, active_requests_count int, waits_per_core_per_minute decimal(20,2), os_start_time_utc datetime2, cpu_count smallint, scheduler_count smallint, major_version_number smallint, minor_version_number smallint ); declare @_srv_name nvarchar (125); declare @_at_server_name varchar (125); declare @_machine_name varchar (125); declare @_server_name varchar (125); declare @_ip varchar (30); declare @_domain varchar (125); declare @_host_name varchar (125); declare @_product_version varchar (30); declare @_edition varchar(50); declare @_sqlserver_start_time_utc datetime2; declare @_os_cpu decimal(20,2); declare @_sql_cpu decimal(20,2); declare @_pcnt_kernel_mode decimal(20,2); declare @_page_faults_kb decimal(20,2); declare @_blocked_counts int; declare @_blocked_duration_max_seconds bigint; declare @_total_physical_memory_kb bigint; declare @_available_physical_memory_kb bigint; declare @_system_high_memory_signal_state varchar (20); declare @_physical_memory_in_use_kb decimal(20,2); declare @_memory_grants_pending int; declare @_connection_count int; declare @_active_requests_count int; declare @_waits_per_core_per_minute decimal(20,2); declare @_os_start_time_utc datetime2; declare @_cpu_count int; declare @_scheduler_count int; declare @_major_version_number smallint; declare @_minor_version_number smallint; declare @_int_variable int; declare @_smallint_variable smallint; declare @_tinyint_variable tinyint; declare @_bigint_variable bigint; declare @_result table (col_bigint bigint null, col_int int null, col_varchar varchar(125) null, col_decimal decimal(20,2) null, col_datetime datetime2 null); IF @verbose >= 1 PRINT 'Extracting server names from @servers ('+@servers+') parameter value..'; ;WITH t1(srv_name, [Servers]) AS ( SELECT CAST(LEFT(@servers, CHARINDEX(',',@servers+',')-1) AS VARCHAR(500)) as srv_name, STUFF(@servers, 1, CHARINDEX(',',@servers+','), '') as [Servers] -- UNION ALL -- SELECT CAST(LEFT([Servers], CHARINDEX(',',[Servers]+',')-1) AS VARChAR(500)) AS srv_name, STUFF([Servers], 1, CHARINDEX(',',[Servers]+','), '') as [Servers] FROM t1 WHERE [Servers] > '' ) INSERT @_tbl_servers (srv_name) SELECT ltrim(rtrim(srv_name)) FROM t1 OPTION (MAXRECURSION 32000); IF @verbose >= 2 BEGIN SELECT @_int_variable = COUNT(1) FROM @_tbl_servers; PRINT 'No of servers to process => '+CONVERT(varchar,@_int_variable)+''; SELECT [RunningQuery] = 'select * from @_tbl_servers', * FROM @_tbl_servers; END -- Extract output column names ;WITH t1(column_name, [Columns]) AS ( SELECT CAST(LEFT(@output, CHARINDEX(',',@output+',')-1) AS VARCHAR(500)) as column_name, STUFF(@output, 1, CHARINDEX(',',@output+','), '') as [Columns] -- UNION ALL -- SELECT CAST(LEFT([Columns], CHARINDEX(',',[Columns]+',')-1) AS VARChAR(500)) AS column_name, STUFF([Columns], 1, CHARINDEX(',',[Columns]+','), '') as [Columns] FROM t1 WHERE [Columns] > '' ) INSERT @_tbl_output_columns (column_name) SELECT ltrim(rtrim(column_name)) FROM t1 OPTION (MAXRECURSION 32000); IF @verbose >= 2 BEGIN SELECT @_int_variable = COUNT(1) FROM @_tbl_output_columns; PRINT 'No of columns to return in result => '+CONVERT(varchar,@_int_variable)+''; SELECT [RunningQuery] = 'select * from @_tbl_output_columns', * FROM @_tbl_output_columns; END DECLARE cur_servers CURSOR LOCAL FORWARD_ONLY FOR select distinct srvname = sql_instance from dbo.instance_details where is_available = 1 and (@servers is null or sql_instance in (select srv_name from @_tbl_servers)); OPEN cur_servers; FETCH NEXT FROM cur_servers INTO @_srv_name; --set quoted_identifier off; WHILE @@FETCH_STATUS = 0 BEGIN if @verbose = 1 print char(10)+'***** Looping through '+quotename(@_srv_name)+' *******'; set @_linked_server_failed = 0; set @_at_server_name = NULL; set @_machine_name = NULL; set @_server_name = NULL; set @_ip = NULL; set @_domain = NULL; set @_host_name = NULL; set @_product_version = NULL; set @_edition = NULL; set @_sqlserver_start_time_utc = NULL; set @_os_cpu = NULL; set @_sql_cpu = NULL; set @_pcnt_kernel_mode = NULL; set @_page_faults_kb = NULL; set @_blocked_counts = NULL; set @_blocked_duration_max_seconds = NULL; set @_total_physical_memory_kb = NULL; set @_available_physical_memory_kb = NULL; set @_system_high_memory_signal_state = NULL; set @_physical_memory_in_use_kb = NULL; set @_memory_grants_pending = NULL; set @_connection_count = NULL; set @_active_requests_count = NULL; set @_waits_per_core_per_minute = NULL; set @_os_start_time_utc = NULL; set @_cpu_count = NULL; set @_scheduler_count = NULL; set @_major_version_number = NULL; set @_minor_version_number = NULL; -- If not local server if (CONVERT(varchar,SERVERPROPERTY('MachineName')) = @_srv_name) set @_isLocalHost = 1 else begin set @_isLocalHost = 0 begin try --set @_sql = "SELECT @@servername as srv_name;"; --set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; exec sys.sp_testlinkedserver @_srv_name; end try begin catch print ' ERROR => Linked Server '+quotename(@_srv_name)+' not connecting.'; set @_linked_server_failed = 1; --fetch next from cur_servers into @_srv_name; --continue; end catch; end -- [@@SERVERNAME] => Create SQL Statement to Execute if @_linked_server_failed = 0 and (@output is null or exists (select * from @_tbl_output_columns where column_name = 'at_server_name')) begin delete from @_result; set @_sql = "SELECT [at_server_name] = CONVERT(varchar, @@SERVERNAME )"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_at_server_name = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [machine_name] => Create SQL Statement to Execute if @_linked_server_failed = 0 and (@output is null or exists (select * from @_tbl_output_columns where column_name = 'machine_name')) begin delete from @_result; set @_sql = "select CONVERT(varchar,SERVERPROPERTY('MachineName')) as [machine_name]"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_machine_name = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [server_name] => Create SQL Statement to Execute if @_linked_server_failed = 0 and (@output is null or exists (select * from @_tbl_output_columns where column_name = 'server_name')) begin delete from @_result; set @_sql = "select CONVERT(varchar,SERVERPROPERTY('ServerName')) as [server_name]"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_server_name = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [ip] => Create SQL Statement to Execute if @_linked_server_failed = 0 and (@output is null or exists (select * from @_tbl_output_columns where column_name = 'ip')) begin delete from @_result; set @_sql = "SELECT [ip] = CONVERT(varchar, CONNECTIONPROPERTY('local_net_address') )"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_ip = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [domain] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'domain') ) begin delete from @_result; set @_sql = "select default_domain() as [domain];"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_domain = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [host_name] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'host_name') ) begin delete from @_result; set @_sql = "select CONVERT(varchar,SERVERPROPERTY('ComputerNamePhysicalNetBIOS')) as [host_name]"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_host_name = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [product_version] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'product_version') ) begin delete from @_result; set @_sql = "select CONVERT(varchar,SERVERPROPERTY('ProductVersion')) as [product_version]"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_product_version = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [edition] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'edition') ) begin delete from @_result; set @_sql = "select CONVERT(varchar,SERVERPROPERTY('Edition')) as [Edition]"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_edition = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [sqlserver_start_time_utc] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'sqlserver_start_time_utc') ) begin delete from @_result; set @_sql = "select [sqlserver_start_time_utc] = DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), sqlserver_start_time) from sys.dm_os_sys_info as osi"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_datetime) exec (@_sql); -- set @_ip select @_sqlserver_start_time_utc = col_datetime from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [os_cpu] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'os_cpu') ) begin delete from @_result; set @_sql = " SET QUOTED_IDENTIFIER ON; SELECT system_cpu FROM ( SELECT DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE()) AS event_time ,DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE())) AS event_time_utc ,100-record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS sql_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS idle_system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/UserModeTime)[1]', 'bigint')/10000 AS user_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/KernelModeTime)[1]', 'bigint')/10000 AS kernel_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/PageFaults)[1]', 'bigint')*8.0 AS page_faults_kb ,record FROM ( SELECT TOP 1 timestamp, CONVERT (xml, record) AS record, cpu_ticks / (cpu_ticks/ms_ticks) as ts_now FROM sys.dm_os_ring_buffers orb cross apply sys.dm_os_sys_info osi WHERE ring_buffer_type = 'RING_BUFFER_SCHEDULER_MONITOR' AND record LIKE '%<SystemHealth>%' ORDER BY [timestamp] DESC ) AS rd ) as t; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_os_cpu = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [sql_cpu] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'sql_cpu') ) begin delete from @_result; set @_sql = " SET QUOTED_IDENTIFIER ON; SELECT sql_cpu FROM ( SELECT DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE()) AS event_time ,DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE())) AS event_time_utc ,100-record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS sql_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS idle_system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/UserModeTime)[1]', 'bigint')/10000 AS user_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/KernelModeTime)[1]', 'bigint')/10000 AS kernel_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/PageFaults)[1]', 'bigint')*8.0 AS page_faults_kb ,record FROM ( SELECT TOP 1 timestamp, CONVERT (xml, record) AS record, cpu_ticks / (cpu_ticks/ms_ticks) as ts_now FROM sys.dm_os_ring_buffers orb cross apply sys.dm_os_sys_info osi WHERE ring_buffer_type = 'RING_BUFFER_SCHEDULER_MONITOR' AND record LIKE '%<SystemHealth>%' ORDER BY [timestamp] DESC ) AS rd ) as t; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_sql_cpu = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [pcnt_kernel_mode] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'pcnt_kernel_mode') ) begin delete from @_result; set @_sql = " SET QUOTED_IDENTIFIER ON; SELECT kernel_mode_time_ms * 100 / (user_mode_time_ms + kernel_mode_time_ms) as [pcnt_kernel_mode] FROM ( SELECT DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE()) AS event_time ,DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE())) AS event_time_utc ,100-record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS sql_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS idle_system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/UserModeTime)[1]', 'bigint')/10000 AS user_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/KernelModeTime)[1]', 'bigint')/10000 AS kernel_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/PageFaults)[1]', 'bigint')*8.0 AS page_faults_kb ,record FROM ( SELECT TOP 1 timestamp, CONVERT (xml, record) AS record, cpu_ticks / (cpu_ticks/ms_ticks) as ts_now FROM sys.dm_os_ring_buffers orb cross apply sys.dm_os_sys_info osi WHERE ring_buffer_type = 'RING_BUFFER_SCHEDULER_MONITOR' AND record LIKE '%<SystemHealth>%' ORDER BY [timestamp] DESC ) AS rd ) as t; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_pcnt_kernel_mode = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [page_faults_kb] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'page_faults_kb') ) begin delete from @_result; set @_sql = " SET QUOTED_IDENTIFIER ON; SELECT page_faults_kb FROM ( SELECT DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE()) AS event_time ,DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), DATEADD (ms, -1 * (ts_now - [timestamp]), GETDATE())) AS event_time_utc ,100-record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS sql_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS idle_system_cpu ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/UserModeTime)[1]', 'bigint')/10000 AS user_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/KernelModeTime)[1]', 'bigint')/10000 AS kernel_mode_time_ms ,record.value('(Record/SchedulerMonitorEvent/SystemHealth/PageFaults)[1]', 'bigint')*8.0 AS page_faults_kb ,record FROM ( SELECT TOP 1 timestamp, CONVERT (xml, record) AS record, cpu_ticks / (cpu_ticks/ms_ticks) as ts_now FROM sys.dm_os_ring_buffers orb cross apply sys.dm_os_sys_info osi WHERE ring_buffer_type = 'RING_BUFFER_SCHEDULER_MONITOR' AND record LIKE '%<SystemHealth>%' ORDER BY [timestamp] DESC ) AS rd ) as t; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_page_faults_kb = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [blocked_counts] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'blocked_counts') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select count(*) as blocked_counts --, max(wait_time)/1000 as wait_time_s from sys.dm_exec_requests r with (nolock) where r.blocking_session_id <> 0 and wait_time >= ("+convert(varchar,@blocked_threshold_seconds)+"*1000) -- Over 60 seconds " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_blocked_counts = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [blocked_duration_max_seconds] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'blocked_duration_max_seconds') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; declare @_wait_time_s bigint = 0; select @_wait_time_s = floor(max(wait_time)/1000) --,count(*) as blocked_counts from sys.dm_exec_requests r with (nolock) where r.blocking_session_id <> 0 and wait_time >= ("+convert(varchar,@blocked_threshold_seconds)+"*1000) -- Over 60 seconds select isnull(@_wait_time_s,0) as [blocked_duration_max_seconds]; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_bigint) exec (@_sql); -- set @_ip select @_blocked_duration_max_seconds = col_bigint from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [total_physical_memory_kb] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'total_physical_memory_kb') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select osm.total_physical_memory_kb --,osm.available_physical_memory_kb --,case when system_high_memory_signal_state = 1 then 'High' else 'Low' end as [Memory State] --,opm.physical_memory_in_use_kb --,opm.memory_utilization_percentage from sys.dm_os_sys_memory osm, sys.dm_os_process_memory opm; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_bigint) exec (@_sql); -- set @_ip select @_total_physical_memory_kb = col_bigint from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [available_physical_memory_kb] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'available_physical_memory_kb') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select --osm.total_physical_memory_kb osm.available_physical_memory_kb --,case when system_high_memory_signal_state = 1 then 'High' else 'Low' end as [Memory State] --,opm.physical_memory_in_use_kb --,opm.memory_utilization_percentage from sys.dm_os_sys_memory osm, sys.dm_os_process_memory opm; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_bigint) exec (@_sql); -- set @_ip select @_available_physical_memory_kb = col_bigint from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [system_high_memory_signal_state] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'system_high_memory_signal_state') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select --osm.total_physical_memory_kb --osm.available_physical_memory_kb case when system_high_memory_signal_state = 1 then 'High' else 'Low' end as [Memory State] --,opm.physical_memory_in_use_kb --,opm.memory_utilization_percentage from sys.dm_os_sys_memory osm, sys.dm_os_process_memory opm; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_varchar) exec (@_sql); -- set @_ip select @_system_high_memory_signal_state = col_varchar from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [physical_memory_in_use_kb] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'physical_memory_in_use_kb') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select --osm.total_physical_memory_kb --osm.available_physical_memory_kb --,case when system_high_memory_signal_state = 1 then 'High' else 'Low' end as [Memory State] opm.physical_memory_in_use_kb --,opm.memory_utilization_percentage from sys.dm_os_sys_memory osm, sys.dm_os_process_memory opm; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_physical_memory_in_use_kb = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [memory_grants_pending] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'memory_grants_pending') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; declare @object_name varchar(255); set @object_name = (case when @@SERVICENAME = 'MSSQLSERVER' then 'SQLServer' else 'MSSQL$'+@@SERVICENAME end); SELECT cntr_value FROM sys.dm_os_performance_counters WITH (NOLOCK) WHERE 1=1 and [object_name] like (@object_name+':Memory Manager%') AND counter_name = N'Memory Grants Pending' " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_memory_grants_pending = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [connection_count] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'connection_count') ) begin delete from @_result; set @_sql = " --SET QUOTED_IDENTIFIER ON; select count(*) as counts from sys.dm_exec_connections with (nolock) " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_connection_count = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [active_requests_count] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'active_requests_count') ) begin delete from @_result; set @_sql = " SET NOCOUNT ON; exec usp_active_requests_count; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_active_requests_count = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [waits_per_core_per_minute] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'waits_per_core_per_minute') ) begin delete from @_result; set @_sql = " SET NOCOUNT ON; exec usp_waits_per_core_per_minute; " -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_decimal) exec (@_sql); -- set @_ip select @_waits_per_core_per_minute = col_decimal from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [os_start_time_utc] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'os_start_time_utc') ) begin delete from @_result; set @_sql = "select [os_start_time_utc] = DATEADD(mi, DATEDIFF(mi, getdate(), getutcdate()), dateadd(SECOND,-osi.ms_ticks/1000,GETDATE())) from sys.dm_os_sys_info as osi"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_datetime) exec (@_sql); -- set @_ip select @_os_start_time_utc = col_datetime from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [cpu_count] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'cpu_count') ) begin delete from @_result; set @_sql = "select osi.cpu_count /* osi.scheduler_count */ from sys.dm_os_sys_info as osi"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_cpu_count = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [scheduler_count] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'scheduler_count') ) begin delete from @_result; set @_sql = "select osi.scheduler_count from sys.dm_os_sys_info as osi"; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_scheduler_count = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [major_version_number] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'major_version_number') ) begin delete from @_result; set @_sql = " declare @server_major_version_number tinyint; SET @server_major_version_number = CONVERT(tinyint, SERVERPROPERTY('ProductMajorVersion')) if @server_major_version_number is null begin ;with t_versions as ( select CONVERT(varchar,SERVERPROPERTY('ProductVersion')) as ProductVersion ,LEFT(CONVERT(varchar,SERVERPROPERTY('ProductVersion')), CHARINDEX('.',CONVERT(varchar,SERVERPROPERTY('ProductVersion')))-1) AS MajorVersion ) select @server_major_version_number = MajorVersion from t_versions; end select [@server_major_version_number] = @server_major_version_number; "; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_major_version_number = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- [minor_version_number] => Create SQL Statement to Execute if @_linked_server_failed = 0 and ( @output is null or exists (select * from @_tbl_output_columns where column_name = 'minor_version_number') ) begin delete from @_result; set @_sql = " declare @server_product_version varchar(20); declare @server_major_version_number tinyint; declare @server_minor_version_number smallint; SET @server_product_version = CONVERT(varchar,SERVERPROPERTY('ProductVersion')); SET @server_major_version_number = CONVERT(tinyint, SERVERPROPERTY('ProductMajorVersion')); if @server_major_version_number is null begin ;with t_versions as ( select CONVERT(varchar,SERVERPROPERTY('ProductVersion')) as ProductVersion ,LEFT(CONVERT(varchar,SERVERPROPERTY('ProductVersion')), CHARINDEX('.',CONVERT(varchar,SERVERPROPERTY('ProductVersion')))-1) AS MajorVersion ) select @server_major_version_number = MajorVersion from t_versions; end declare @server_minor_version_number_intermediate varchar(20); set @server_minor_version_number_intermediate = REPLACE(@server_product_version,CONVERT(varchar,@server_major_version_number)+'.'+CONVERT(varchar, SERVERPROPERTY('ProductMinorVersion'))+'.',''); if(@server_minor_version_number_intermediate is null) begin ;with t_versions as ( select replace(@server_product_version,CONVERT(varchar,@server_major_version_number)+'.','') as VrsnString ) select @server_minor_version_number_intermediate = REPLACE(@server_product_version,CONVERT(varchar,@server_major_version_number)+'.'+LEFT(VrsnString,CHARINDEX('.',VrsnString)-1)+'.','') from t_versions; end set @server_minor_version_number = left(@server_minor_version_number_intermediate,charindex('.',@server_minor_version_number_intermediate)-1); SELECT [@server_minor_version_number] = @server_minor_version_number "; -- Decorate for remote query if LinkedServer if @_isLocalHost = 0 set @_sql = 'select * from openquery(' + QUOTENAME(@_srv_name) + ', "'+ @_sql + '")'; begin try insert @_result (col_int) exec (@_sql); -- set @_ip select @_minor_version_number = col_int from @_result; end try begin catch -- print @_sql; print char(10)+char(13)+'Error occurred while executing below query on '+quotename(@_srv_name)+char(10)+' '+@_sql; print ' ErrorNumber => '+convert(varchar,ERROR_NUMBER()); print ' ErrorSeverity => '+convert(varchar,ERROR_SEVERITY()); print ' ErrorState => '+convert(varchar,ERROR_STATE()); --print ' ErrorProcedure => '+ERROR_PROCEDURE(); print ' ErrorLine => '+convert(varchar,ERROR_LINE()); print ' ErrorMessage => '+ERROR_MESSAGE(); end catch end -- Populate all details for single server inside loop if @_linked_server_failed = 0 begin insert #server_details ( [srv_name], [at_server_name], [machine_name], [server_name], [ip], [domain], [host_name], [product_version], [edition], [sqlserver_start_time_utc], [os_cpu], [sql_cpu], [pcnt_kernel_mode], [page_faults_kb], [blocked_counts], [blocked_duration_max_seconds], [total_physical_memory_kb], [available_physical_memory_kb], [system_high_memory_signal_state], [physical_memory_in_use_kb], [memory_grants_pending], [connection_count], [active_requests_count], [waits_per_core_per_minute], [os_start_time_utc], [cpu_count], [scheduler_count], [major_version_number], [minor_version_number] ) select [srv_name] = @_srv_name ,[@@servername] = @_at_server_name ,[machine_name] = @_machine_name ,[server_name] = @_server_name ,[ip] = @_ip ,[domain] = @_domain ,[host_name] = @_host_name ,[product_version] = @_product_version ,[edition] = @_edition ,[sqlserver_start_time_utc] = @_sqlserver_start_time_utc ,[os_cpu] = @_os_cpu ,[sql_cpu] = @_sql_cpu ,[pcnt_kernel_mode] = @_pcnt_kernel_mode ,[page_faults_kb] = @_page_faults_kb ,[blocked_counts] = @_blocked_counts ,[blocked_duration_max_seconds] = @_blocked_duration_max_seconds ,[total_physical_memory_kb] = @_total_physical_memory_kb ,[available_physical_memory_kb] = @_available_physical_memory_kb ,[system_high_memory_signal_state] = @_system_high_memory_signal_state ,[physical_memory_in_use_kb] = @_physical_memory_in_use_kb ,[memory_grants_pending] = @_memory_grants_pending ,[connection_count] = @_connection_count ,[active_requests_count] = @_active_requests_count ,[waits_per_core_per_minute] = @_waits_per_core_per_minute ,[os_start_time_utc] = @_os_start_time_utc ,[cpu_count] = @_cpu_count ,[scheduler_count] = @_scheduler_count ,[major_version_number] = @_major_version_number ,[minor_version_number] = @_minor_version_number end FETCH NEXT FROM cur_servers INTO @_srv_name; END CLOSE cur_servers; DEALLOCATE cur_servers; -- Return all server details if @result_to_table is null begin set @_sql = "select "+(case when @output is null then "*" else @output end)+" from #server_details;"; print "@result_to_table not supplied. So returning resultset." end else begin declare @table_name nvarchar(125); set @result_to_table = ltrim(rtrim(@result_to_table)); -- set appropriate table name if(left(@result_to_table,1) = '#') -- temp table set @table_name = 'tempdb..'+@result_to_table else begin -- physical table if CHARINDEX('.','dbo.xyz') > 0 set @table_name = @result_to_table; else set @table_name = 'dbo.'+@result_to_table; end -- delete table data if object_id(@table_name) is not null begin set @_sql = "delete from "+@table_name; exec (@_sql); end if object_id(@table_name) is not null and @output is null begin set @_sql = "insert "+@result_to_table+" select * from #server_details;"; print "@result_to_table '"+@result_to_table+"' exist, but no columns specified." end else if object_id(@table_name) is not null and @output is not null begin set @_sql = "insert "+@result_to_table+" ("+@output+") select "+@output+" from #server_details;"; print "@result_to_table '"+@result_to_table+"' exist, and columns specified." end else begin set @_sql = "select "+(case when @output is null then "*" else @output end)+" into "+@result_to_table+" from #server_details;"; print "@result_to_table '"+@result_to_table+"' does exist, so creating same." print @_sql; end end exec (@_sql); print 'Transaction Counts => '+convert(varchar,@@trancount); END set quoted_identifier on; GO |
In the above code, the procedure has parameters that accept comma-separated lists of servers/metrics to collect. We parse these lists and shred the data into table variables to get rid of any SQL Injections possibility. From here, we loop through each server that is qualified and query it using its corresponding Linked Server in combination with OPENQUERY. Below is just a snap inside above-stored procedure body. In this, we can see most of the components involved while fetching one metric at a time.
This stored procedure is quite flexible, efficient, and useful for DBA. I often answer a lot of user queries just from the result of this stored procedure without even connecting to the other SQL Servers in my organization.
I hope this would help any DBA/developer looking to explore an effective usage of a dynamic query, and how to utilize the same to connect to various other servers from a single stored procedure.