/*
Script created by AgentSignaturesToTempTable.sql at Jul  9 2008  4:50PM
*/
IF (OBJECT_ID(N'tempdb.dbo.#SqlAgentSignatures', 'U') IS NULL)
BEGIN
  create table #SqlAgentSignatures (object_name sysname NOT NULL, signature varbinary(max) NOT NULL)
  insert into #SqlAgentSignatures
  values
  ('sp_add_alert',
0xDE0411CC7B74371636EE5DDB6FA5930C12BA8BCEF57ABF5E8242CD330617740BF4CA01C8B1E6BF7EC8182ACBF7110F8469E83D0B35B72C11A67245AE6B4D35FB8212C9EED70B1F3972CE86651799C6D74F99BA54E3B64230332643723BFD2972AB7C9E38E51B54E3E6C257EB32B66DE4CED4A78BBDA2340CEC0248B5ACD07A55)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_alert_internal',
0x53A7F0220BA23E8C9F9F8DF6F1DB7D30E0F2D02C556F59572F724AD46E00C604855A947A352AAE0E281BBE3502283FD046367AE524DC77677F6CCC8BD9CB5E13F96E2BBF76C0FD9CC0692B7B831D42EC2845CB1C15C2FF75A5D183AB44B9C666FEC6CE6708832F0E81CA2CDA0E71BCBDD15FAB5C12213E7354A67F78D56F22A6)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_category',
0x03D68C231947A9BFBDA4CA9DB7C9E30E5357E28B808400B20730418B09B47D9CFA2C50EB5592D41DE892D52F7917DD7159D843AC6AA7F137B34C4FF53F56E03142D51778A5C4E3A9301877646AA47FD23B6761D2465183A0F9B7265527BEE4D0EABBDE9371BF4BE56C1AE77E9D6A3527D4B1BACE730A0DF3807D03B8866A23BD)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_dtscategory',
0xFF896F9B3D5DAC2AD7DEBC81ABB16A4ECD21A8F48EC41874C6B4A676EDB805C2908D1CCCEE23B21E56A1B48632F499E32FFDF103FE2E059AC24BA2BFD71EB663A0E42F1D2B181FB678B7BF1E2A100E8E5972DF7E946FF5F88167F350317B7F513C112FD29F659BBC8EE9C862DE404CD7F71D71F128C0B6B1C7C401F5BA22FA95)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_dtspackage',
0x6031C52E2249BF3C36D6C02682E2FBA0C3AFD3547892AD486D99A9B4EF1F4169778C7F9F36E386E6147E8F5BF41447C8D7C8BC103A536E312C80D4BF6AAF8BAFE225F040DF5F8AC0C3450E86F63863B54F79BF94743985EB1C28B5736E3840E8F0F5E1FD5C042CB699459DAF0EAC6760A0EFD8FCB23F9C54EF235E34B5667BB4)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_job',
0x77F80E3DF60D4233E9BDC1A0A825422D30A1C50C341D9E6686AE08FC07CC6BE92B4E65DF002D04809311183986C8B4AEC62D4AD935D1506C1C8AD0729A2CE0765F108AF3D7BFAB1917D5181CB73679A00D68CD46ED15B6EF24F07A69F3D7ADD65DD4AB83F4CC0C3429331136A96DD41630E66CBD1508D1D46088184928D92D4B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_jobschedule',
0xBDC79C29CB3168B0D6E13B6A3CDA5A73EEECC8F0034D14B817F7E4A129FEDAE5226B5D2122AB31549F26CE3BDEF98DF668F04AD822EC32AA15DCD06B56447F332F2A5470F2D508C94563C138F6DF09972AACE50919CB91381DFAE373FB8F4D6AFB0F71982A4DE1B29A452DAC553AC6B8D9E4898E76619497F432D263E2407E35)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_jobserver',
0x7A6BC95EB55371481EED1889A19FEF9129B4F7436DEFAC4B9B666E422D6E549488F5EE95086C07BE8EEC4D3A6A2B4F063C8DA865D01939EAA3A9A880A96C55846C06DDD7853C759C532ABEC0FE9E8C9E958620887C087DA776A9DBC8E820B3ABCE1F63DFA24F4F603728D45554F3B83F7109267E3C4755678038E847F9512C22)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_jobstep',
0xBD942B0924C36724EE1317B59C2BA6D8519BD0CE4CDFFB3A13B25B925EFD9814FD5E3B7FA92B7746DB61FCEAFC10D3B851904143B68BDED25FD0D9C6CD91035A87D3B25B3ACD78AC56A96BD119287DCE109D42D34C23649FB2BDF6592663EB5AFDFC7F1D6C67EFF689624122644A7A589012F831B8BFC82686FB03F6DF2CA891)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_jobstep_internal',
0x60B4B104A5690EE47A34F2E9148F6678A9D8D6DABAAAC437C5EC3524FDCCBFBA684134CEAFFE2F7AB4F92EDCA06703F5507601B93DE10A5560B00A45D38BCBDF48FAE40E672BD4BB065C33F6707621636D7C59BE41F91011B5DFA7642C86DBBFC3D99E905BF8522072820012C2AF9FAB9E6A2E4C4466B6133A2AB12B251E3A6C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_log_shipping_monitor_jobs',
0x51C1EC5DA1395E528D3CF8F04DCAF61DE97EB783DBBB50E15C3AC3DC268D8D92950C7E64A9FACB66E7E46A077FAD6DC8CE0AC02ED6B571D9BB68EACEFF70E19D572C62A516C92230AF3B04A0A9614C584B26A129143443C0D635C7BBA3EFE672C2A21CF373508F9B96F5808349E59E0C79DFFCF42D0E2A36AD4DB1ABC58469A3)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_log_shipping_primary',
0x4891F5E60B4066790ACE0A97962979332D851ED108316406DEC4D56CF0740DD22F666300290978557D13007C4B27CC5D87891F91ECD9EF2E2CCCF7C6F8408C4A63CAD61C1F8D96763D461351FB1D1A112A86ED2DD38F3AB47E1646A4395B91E3DCABCB2670F99437416321558F0BA45CA61DF5A3D8F1A415BF1BE5B968800906)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_log_shipping_secondary',
0x37C908DABA9748C2A80937FE28B851EB94EE9846FA36DC1A6181E95000B264C82144ECF7418D3B0454748E1C40320DA58D58BDECB00325245DB6404829F82A625F72EC6730C2566CD4AAF57E8D1014ED68886F6702ACE606DA3B529C008966B346B827C875D1D979018D05C919B35537C7325344A1B695BF22FDD274219136A1)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_maintenance_plan',
0x41EC079A23738FD93A4C19F59D01D3999E0993FCEED8460D338DF97C25880362A3CAAB4C74458C5D5781F82A5401681543FA451FC1AF31AB104B96069D44AF1ED8A3F8D595F9EFD9B69656C73F0D86C29A3CEEE04F44E217AD06A3C237A0ABFCFD9E24E79BFB462A44B1F5C2AED23EBE471932D448E00452138028C117E31DBB)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_maintenance_plan_db',
0x8EBF7168A240665992863A5152ADB8BFA15D52CBC030D0C3E9802B3E107D90458EA74190D03BF2D9BC6BAF177DC1D5F34589A5D44DF91226869BE5E660D8E90FF5888606F0391263B1BFAFDBA9ED6BB9B1BB145CC14E26E80AFE7264E168642D9EB6D4C5939F6BF159BA05F7A6427B9220A2178E0215653D673E8F24129F4135)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_maintenance_plan_job',
0x3FD8DFA0B30E12FFC8B94D0BC6CCC0AC6D4BE62A927937A0538C9E27A0DB138CE14BCE1DABD5AF287515FD7E674ABAC718C20CF3DA62F6C39123A30989BF808DEAFD9004EDEAE3537FA6CF0490AD3653DCEEBD9F233C7761685CE8621B515F47C77F2CE6F3F0B563B1E4A3D64F359F7D4F28AC6CE2710916810D2E32AE4357BC)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_notification',
0xFA1CB30E1D5C9F1B3163A924B59D600DD68979DE87C563E1CF8032C4D61F1F54FEFCC9EB0633401C24BB354B4986CAAC233793FBC76C9A8296FDC656232FFDAD8C1129B26B123B2225EBA654C51634D4B6E7FD1C3EBA12E4604B65F53831F8C47287A533690B4D296F26773BDF1020DA18CBA23307D597F585862798720B7E4D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_operator',
0xBD1E851CF0D0AA4307580B05A9709B6F44E471901D1AA80BE3D054CA54641FD22228136A1E5BA0D5340C2957BBFF02B7BA7E79BF797713F522870F36BDDC6CBA276137C17E57A61005637CFF1A907BF196928C16F50AE028702EC77FD5C01595CD4ECB82BBED6780A90C409F03A680E469C7EF708C4BFD32DDF955C6D3DCEF0A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_proxy',
0x42E8041C6E77BE636E55E681219602C648AC1A80A3F687D76EB4CD03AA240CE936868F02670F7B6CFC50810F227D4C8A60862FBB66167CE759B63A81783EFC80744C2CCE639A190FF7B977E02D3F42C57EB627532B5E97F9C468C81B5ECE9F27200DA4626519B4575E8EA81452B4256B74352FFDDECBCE6A64CB8F0DA2AE96C5)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_schedule',
0xD04A6C44F827EC25CA6758A81176A7BA36802F8780D761F39EAB10C6DD39435F73CCA26FB16109E48553FD5E438FBA4929A57083B32E9ABF42B9E263AE3313F73DBE6A7984B9791202C1AAB8E1B2B14D8A6013B8E9A576AE160505FD742467E26584F6F76867439420B9D3B23FEBFEE678F1C702C1ADF67DF59A22E799AEC113)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_targetservergroup',
0xB76829B210DD10B92E0057E12CE94175ECEE29F52C5F39DB96AC82251AA7864B80AF62F6B3D8C54EA751F0743C97A9B4638B77FABB65EB986AA9082C53C749A25AD223189B09418D57B556D471C6FAFF8D5BBE47BC71DFA735BA9C232C891356EDD60B1E814AD8FDD482914182BF529A7FDA60E4FC2490ED2459BE8E5396D636)
 
  insert into #SqlAgentSignatures
  values
  ('sp_add_targetsvrgrp_member',
0x0657AC08A03C9D1AAB01464355A5BC665B08AF15C0598BCC8ABD6C89B30ED9B1421530077DF62A2E9069CB1FC5A656BB08B82E85622D4096E0F216C105CBF06A76B960075CD2C65D8C195602DD5608B83375963A37C5F80F2F9FD924E7E5459D7425822DFB308532DB698702813C5F74E9AF0B6BE850E608CF575198C129905A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_addtask',
0xFF07A283E5161C98F4BF8C3E0D01CD57EEDD275E95E3E3B66B018CD43BB952896FC5B9A8402FEA23296A4A1034CC64FC7BF1F1E8839646B13855A22673E55E6691654E6F1B693D746408F66CC26C28C7466A684071E1A12FD564D6C41CA8DF7A706C3917D3E49CAA1FA1BF50B55358737BF5C25C2AC4CF89644C8221FBC69227)
 
  insert into #SqlAgentSignatures
  values
  ('sp_apply_job_to_targets',
0x3B226330F46F704278051D3EF083A624F152F6D962F1958C23FEE9CB442186BAC67D6346D414E2C637FE6F3ABA86B4861C968171DF13E1E20ED7FD9A4148BD35AC1CCC509C5A55308B190401318A5BBE047536DF4E4E0948DE45DD0DE725BEBE189C4EF0A7F27C4DADA30390EA49C5BEF8FF914CBC1ACF048D02BE2C35890663)
 
  insert into #SqlAgentSignatures
  values
  ('sp_attach_schedule',
0xDB3108B752865D53E79A0790A72FE01AAAF0064DB19F818868B2F92A738EC22B83ABB7B8E390FCD3F59D68FCAC6AD30A6AF317E913A83441D63DF00077A2424617AD79F8AF613E00870C4212D91E679FE691F28544CD01C9FC69D0F7BA63D89F22189CDF9A8F1F904C81A7639AD8C5AE3E86BEC2D30424C350ED71EC5B2C8920)
 
  insert into #SqlAgentSignatures
  values
  ('sp_change_monitor_role',
0x781285FCD310442C58F38B5F6912DE8DCF9B0BAA2538F97C26B938BB3E13C57F684B500DAD854934870DB1639C2B3EF291C234291E22285C7B265ABBEE262B87BCF4A00A95ACF4F1EECFD4E42B3F3DA0FC72F0E0FF394B05BCF27EA95E79891BBDEC72DB6DD58B44D49DE6481B5FD366712C6CD5FF5C3CBA78D99AA6DD34E496)
 
  insert into #SqlAgentSignatures
  values
  ('sp_check_for_owned_jobs',
0x8FEA04B277724C446DA88260D924070F8E219D2C56BAFA7875CF728C65727CB94C471EE1D080799B192D222895DF29863A688D278E10C6E6BB23EBA5A1BD1DA92E7ECDA90C814C2165B85511421D5D86796ECD308CAB081A2667AB228D877643FA534E879464BCF679F6289482DD687E2BECCEE9EB078E4A2D3E3CF350D6FA46)
 
  insert into #SqlAgentSignatures
  values
  ('sp_check_for_owned_jobsteps',
0x80C8AD5229EF7A8D5BFF8FD4E489802B8CBAD244A448DC042BC897C1C98B21546F391B2DE6EE1231EBEDEB88ED4D5CE48D88BEC186BFB181C41A9F2DC5445B561FD95B4BB47B8343A006B9E46610AF482C0F56E09C7DE0D12F5952169DB2E4C787F9CDAFAFBBF3638F9A1BD51C899EEA99AE8F19E3E24E44314AAFB5D75DD23F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_clear_dbmaintplan_by_db',
0xDDC801EB30B922E40557C1F52709CFD929FC5A9161E5DE3BD62164C5BAEB7183A2BFEF4B667705EB4061C2B6670B53BD8DA3EF51890B2360E690E82D8BF5443C7051216AA8797DB10839701D2CC8182CDEF95553271E93C755E5886910D12011782B1A58B61D02E99A6B5C8FBD8E7CFDF285530F34C0215B84958CE6FE3194BC)
 
  insert into #SqlAgentSignatures
  values
  ('sp_convert_jobid_to_char',
0x76B1D9D3D9F3891B6EC6A0A5EFEF4BC2680FD5F7D49AC700ECA5E497CE90F95C85FE0067A861D6C8AD8062C14F4092EFEF2AAA867AA7A23921C3472E4FD55DEA2F8E2348990C9253C751B7DDDD35374D1EA342E015A2FA5C7B3F0AA855F6E2B7CAF42B02C384CC4A8693E28A969521394B60D82199082E90AAF045AF2A112151)
 
  insert into #SqlAgentSignatures
  values
  ('sp_create_log_shipping_monitor_account',
0xEEB737577827A38B5BD462836D2DD8CC293228861E1DDA32163A5CF9703DE4C03B80057F77D8D65E7C175E7DF13F19AC433EDB419D6F5F310797AA87D2ACB91189D4A02CCB8E9D91C768D2273848941F01AA86211A9E34198E18AED161119DFA568C408C7E98D26C6EBED7EC1C97483F70714CA5705E18705CB1AA9F95759D01)
 
  insert into #SqlAgentSignatures
  values
  ('sp_cycle_agent_errorlog',
0xE1F7CA6EBB9E6A41E0D42C74A2F3922233253D5DAD6D30D0E1378BAD12684A824368317985B5169039D40FC663B2046B8100CA6C5019526F9FD143EE390CC48521DAA7DCC40D3E15ACFAAA8274BD595967402962DE30E189B6C593BFF0AE138550D4F9B192842DD7F236BC0D09542D5D864F4B644D5270F1792BB9F012E8727F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_alert',
0xFF0584E010D17460BF4E5B307023C11E11B4753774058F67F0025F16C66CD0914C7CE6E8BE2E2A41B3577F476BCC90386403CFB80B779F25567F3795F9955662EE0AC9CDAAD2EEF36B2AC3DAF71EC4E1916661029FA2A734F60BBCD193D00272C5F6539BE2F789678740AD12F9B4712E2C56233C3A87D86D5BB7BA47E147787E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_all_msx_jobs',
0x010E1B2FDD09039AA1FE2BFD2D7A762B7C02A60F664194EF5A4F750A94DFFA9BC7FA703B82AAA8C135BED25C7134D7089D3B69EBF570F27AE312CFBDB8C6C460559F6A9472D9D08A0BE98079FC977A6310AE4EEBF3D6CC16288845BDF7708E7EF2B24F1C4ED832EE82282FEF2632E678A6BE2900645981E22574D47BF3BC2689)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_category',
0xF78156EFC7E8A8100B355C6B38A13309079E978BD28E7FBA68CF830E635DE2CA312EFAFD5A6A7FB44D6D7539DCF7031CBD5E9C562CE438C399D83104A8FAF5A87F0BCEFFE17D1F5D4796A69EE07A32349EFFBC12761DF0808ED408D63DD056D88450FA7DFAB505371CAF810A3202D35298D7DD36CE44EC92513F7023BAC90103)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_job',
0x7A1CF7C86ED078DD4048E8D564A909859FFD016F043AA8F5888B81FBC5DECFBB4102C4F1CF4A47B9D20782F631BB4BA0124400B15AE49177696C6A4917CF1EA6ACA709807BEF8E7487DF88DD0CD0B4E3A441C9B65EECEC1375D942F7DD46394C76B3CB632AB660E1145EE9119C5C9E9D655DC66BAC53EF2E0565C789B2961BC0)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_job_references',
0xBE82E63C3655E04EEE30A6F46EF11349325F232CFCE5E9D476E539DB970C3E0F579AC9AE8E488CF79AA3E16D82E9E3F292AD447282ED6B55EDF4995DF2DD10A285DDCF53C370DEE00F93F2292390DC479530D6EF92AEAAADB62339D52245010F7BAFBAA958E5A47298BF30AC55A163B2E817CE846F9811E7D78351393FE85F4D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_jobschedule',
0x849480482554FECD8C8F0DD8EA4533CF7836E72AA02F669C8E3D7DCFD6919185816835DB6E6F64FCB9C5D435310F74EA0FEA38298F10975AC6335A113AF50B63EA6D8A98A6B8E54D11A2DFC33470848C0E7141D7D5B369D5EAE725ABD10F09BA6B5BB6C37DD859C9B36CC601971B6E148C191953CCE7B815B175006ED1462B47)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_jobserver',
0x62C10E073B647E13AB53593A675F129817FD7090DFD6D39C3A26A2BF2E2CCB196157D503CFAB8F290BFF66AF9393956AEF32B507094509FAF3BEF0FABCBDD47CCA8138EAEB6C7FBDCC41CA9D1CA159B4F151064D41D658DA35F69FCB9084013BB7EBF92349C49128FA1997512579B87635EC6583E8CD695B90F4804569359DC5)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_jobstep',
0xD27EBCD093EE4359605FD763C0DA4C954A7CBC92C23EB1BE56E452CF381DE0373CB6B5F9936B68374CB1E45DC7D90DBED10031C0E6133809036AEB4CFCC8357C3789FA93CAB9BE75AB7637E40B90A023B529C4D092F71A88B762F4205F0B515D9DDBF197595DFA1402A43F835D4C769EF4BE65179BF53430912A9ED693B0D588)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_jobsteplog',
0xE2C123CFD287A2FE979055F97A1A08D80042B0FB5F95010D4E86BAA0D7C502AF05C94F4F53DDB8C250E33F25A88AA8D9FD3E4D6A0D48320FC78B48F16885882716AC85F2273EC8B6AF9B23511ED9944E7FE81FD825BF2B97FBA6624E6142E1041B2A1261D85D8B29A8635E684FCC4A865150FB1895DA956971CA801CCA2762B5)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_log_shipping_monitor_info',
0x0C8F42AB871E301E44B2D2FAD1B683CFBEF061DC344732B58FF65E36E662769E1AA5854FB19F478B518143F67A49A592CCF9E06DFB17BF1AAB42749B7AABEFC3E95DAE53B9345BC9DAC13DD94220E97C9C10B24D5FE3D25A36FFE637FBFB82614D5AFE18C400C8569C670BA7EFFFBB6B335FF63D019A0EC755158AAF5FC1A446)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_log_shipping_monitor_jobs',
0xB99C653741ECB154E3597B46B44B72A97A8E8BA3BAE77B189B3A3B567C6BA718784E6DF4078958EBD56AF31C9B4805D3E9762679902440695D292E7B5DDCD8D22410C0C2A257843F4A44352FE176DE79FC61940250A3CDBB0383B5F6436ACD48C5991DB797825128EBCF4B04B89FBB70C34601C4C0DEBE1E227A603592DBD985)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_log_shipping_primary',
0xA4842111CB0AF1361F5EE0777176530E556A309473588314A36ED6BBBB0562212B6245B1F16FEFF5E3B79A0BC93C521E3A5EC081B351F173AC40E203BA624DC5D044882629ECCE5E31997FADF29DBE600C58D059BAC01261CBBEA6194D9D80CDBD06AB0B412BF8FAA75558E3EE1AC9E7E5BB18C3BF0745542711F868652BF691)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_log_shipping_secondary',
0x33E9679210BB5C3CEC328958A56909303EBAF46A2E6DB3DEAE7D1B8BD9D1E0F99E8D0EE7497E068372D012DD7E42A60E9F599EDECC6AF4A5A6091F9C25D12FA7D2DD2976726E415A1D1536D2A5078610891DE09165FB6E7E97B1456AB95C4DC500E14EC2E2EC1850939213AAA0EAA04294763977A3DD557BE60C1553918B269C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_maintenance_plan',
0x1467F4FFFAD462025947AD8A676E9A04B0E41808CC415637C2340655980F7A13695DD3330F604F99784D467807D2C576E92C23CF7C178ECF5211052AA66258C26EA083F9EFBA211FB8C3C1674BA58E162D6B5A3ED331B960CC0F206E34CE374C124FFB0281D6CB1C93994A5FB47D6CE84F78F7E9576B2529D4247421D70E245D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_maintenance_plan_db',
0xA00A1E816A9E4F7CA3BDA1F3A6351D2CBCA7A9C36DFE26CCBAACB36E007F2623811CC8244F942489FA7CA57B72A921DF0CB50F7E97AE88F47805A5A211733A6A99679C07B723799B5D514C81480913399822F2EA7A8B50826D587DA22DE63DD624861E40911A3E671488E2F6395E2525BC5ECA0E8F94B986C3A1B0CA9AABFF6E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_maintenance_plan_job',
0x9A1C1D56ECD066B01B9A2A30C99BC7C8E2CD3103B3AFCC5768FB54D54EE8EA26586BB3E1A0D009C4DCDD79E75DD8FCCC1A59530E1E45956AAA50F87FC81ADBB5A14A113287A8D055EBC53898A8C548A1BFF22BE1086A4BBC4C27CB301C838D22AD17695D04964EA3A64E7FD912430F799AF17AC5510EB2EAE946E8B90917ED3F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_notification',
0x0A751567DF1E28FBE1249F774BA02B2AD574CD10B264B74B57DAC5032409320240AAC013D7C4CD9E910B81DCB69CDB68CE41728E8E24807A6DA1B2F2E3A8D90080A1BB1974993E2088638260E61C198FBD5F4D16F0FC01432D6153403E80A504327FD5868829D1FC31E625838528AC0A84FFD14A9111EFB2F38FF5DFBA18A926)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_operator',
0x909666DB091048307DE3ABA608294E57CC254A1A2BBB4D83E18FF5D28921CD135416677E6DA0FA598864F20F9373F57650B71B8AF381331F6BA5D7BF65B56E7FE0DDE960232C7C6EAA94DC70221008FFF1CD383F04F438C8DAC3F8817D8D624A3F75BA0F220CEF347B2AC0573F31C3B162574BB2538821E5D696D1F92A27B82D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_proxy',
0x1B1B03FEF51B6869E8C3656B2920C3195692D39B49CA33ADF6B6D4C62536B5A886DF16408B5DE851AE8059B8D919AEA673496ABFED8F86E51464E46AF89B92B5EFD29D1FC987FAAA7C41713B81EEFEF861F28F70CEB1D0621A46D4363C936BA696F8854805113E293971A6B8A0DDE933AEF9D085D64C3AC898C5183CB77E0514)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_schedule',
0xCB08C016DCEDB7B859467D6BC7CF348A43EAA7102E98E440F2F3A9F6FB6859A17FEF1B0E2A6BFFA8045C88A3313CE2DB8AB6ED3A3ACF9E13348674C465FA245C6E6792A2E62FE1F77161F81C9A9DE3BB4EE0778B7A68B306C9236620BF7C98A83941F888CDB5DDEE84CA0C9F7D011D5880B003CAD322E424C5352D7055BA6C6B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_targetserver',
0x9950859C1D465F191DE5A032A97C65AF6E55B6C66070635093AEE1ECE78A127887E41E2F4DAEEE4D3101DDDE501FD56ED3C339FE0E6E0EBB10D774915ABC7FF4C0E4F13911127FC1806D1511DD82E2D1FD6C54B4C1CECB740914DF7C18F261920DE140A0B3FC3629C94F08DF77241EC01021209A15DA25D5ED7A1AC9C1A46D0D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_targetservergroup',
0xC9C4D53E5DED09E2EDCB95CD1D5C62E1C864A12871FC216D9B49C3982AC3203F1825A013ECB8478D78388B89DAE51303581F8031CC61D88B85FF56F548E26A7E228DDFE2682634E3A6496455974CA3BBE8108DB49C695C7E5805293A3E207C7F7262FCE9B94E7ACF6D79BCDEAF387E89A06E31B2FC29E039367E291895B1F185)
 
  insert into #SqlAgentSignatures
  values
  ('sp_delete_targetsvrgrp_member',
0x15661386691BD06AF9DD8BE18230589DF61E4BAAA52635DA4FFFF6E65C8945C467BA9EAC1330668B6586D87E20F15EE6CA968D0CF0C88237D549493C0EB7FA470994F3327FDFDD2BA8F3E018317105DF7D3CCD87F499CD6E864C7C0BB1BFFDCBCEFEC8F646409BB8D5C41D4939535BE30E1826B92C32A5CBD675936D60CEABA3)
 
  insert into #SqlAgentSignatures
  values
  ('sp_detach_schedule',
0x331176FFDB9055B760653370E75951F1845B50BA0C0435FE8AFEA08EE1A4E7B9558CC3DDC66D3D8FD48D05136E436B2E83C2E551332A886D909E8865678285097B5968401C512E544EC6E1ADBA6200E8E55452367A30C8910AE3DC352EA6061811C2AD5E4C1CE0F8411BB6E31B599365C4CC28E298C3E9DE7F085172FC7D360C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_downloaded_row_limiter',
0xD2D0FC63E193AC45125491F5FAC873F68E3D8CE740C533AF075C72674EF657F0132D234262CD9C607EB5B6DAF096178BAE72F40BAAF340B4F107E508EDCDDBBDD06B1E90219CCE1272CB881E5624C5F3C8385D75B1AF749503E5AD1B663DB59F4F0C4715328F40F9185F8F0B67C205B258F5EBC4E31984079C6CB62A1CD22AA0)
 
  insert into #SqlAgentSignatures
  values
  ('sp_drop_dtscategory',
0x9A7626A8A1ACFC80F4B098031657736E3E691028216E82EF73C8E1DB5DF3A7B5F2792C001181E945E2D0EC4BF4F612008A52A401D1AB47E0CC0E50ED16877BABB56F74F0DB34ACDC7C58E2FEF8621BA7467F60E4D07ACE69B7A3D722D759606EFDAB78DAED84B6E43624D216C627DB77890EA7E78D8EBD1044E93B841320D70B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_drop_dtspackage',
0x82B2715777A21BAC650A27D9287B217A6BBCCB007171D30D19DF40176DCF53264EB3A31F98FA8D553BC530DC7840465D455F49304A49F28382B7292DC47AC3E410190A79DDA885424BEC30C1D21867DB883E9BA1D87AF01E80725F3F808D1AB2A960CED5EB3DC109C3B945F29E6F70AC6C03395CF715A856BAF4DCA68A645079)
 
  insert into #SqlAgentSignatures
  values
  ('sp_droptask',
0x64462DFB5186DDB4ED981160F0B42527E34A588B6D647E2E331213EB832927A8BAA8CFC8B060DFA074CB38FFD2FA7B909BA837A6F875673F2AC0BB010E4EBCD6F76FA7BB64B69FE5E20C751956D99151017E8BA7517B1040F14523307302A295F0C62BBA79A27475660CDBC09663AF2765A4F5F104C11706B9083F937000B467)
 
  insert into #SqlAgentSignatures
  values
  ('sp_dts_secure',
0x7970784B6623B20F85EA64D416FFAD0A46AFD1F4FE83076FA66981025C7277356D2C082D3C87C7A3DF8506E47063165CAC9237BD8A9643E061EEB3BE056ED94B2918BDBB79A85269D7F98367C5610363AE8947599FA48E7AC424DCBCC1156939520F87BE8970C5F813AD1CADB25200F033FA8364BFD48994525D34AF2E784D8E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_dump_dtslog_all',
0xF02EE6C479B7BD0EFD7686A4D243E9C5E681BE1A98404FD02EF6B19150B6CA9DB9461A690D5BA76F492D3CAD49DC1B8A216B07BE3A41EE5852584F1C8891B6E9C075B1E2589328FB3201CB6DDFDF415ACE8301724464CC7A02563CD1EB43561177E0990A5700F0BE432DF89B459BF4D879B4B5D854D2A96794BABF8E822A5410)
 
  insert into #SqlAgentSignatures
  values
  ('sp_dump_dtspackagelog',
0x98AB3FB70D0A191885C04C45DACEDC06048F605B6241884203814E74D31E62462CFF99BB1EECE5F931B8758797E7E2B1EBB65110B2D0FCE58D55646E844818C7B694ECB1FFCD3137E3755CA4FA3A7EB5D5891886792AA8A10A51DF8F4B8BA782C21C488893176AC7821CAC2D2A3EF083C40E64A28C0D360EC3C5824B21AEF46C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_dump_dtssteplog',
0x9163F876B5AC2E8B7935E59C71CF27A0AC5B9A4184D3B55D39FB7625B3EC86B73B6806A5C63079803ABFC2A108A642FA30EB1B3B7400A579EFB8B35D3B7E2DC4758648B715D8DB77EDEAEE901099956EDACCE536A5B23F56F47F4A23A38206C48EE5E6820D7559079827089035EC6D373785BC6E2BF5F462CBB5312333647131)
 
  insert into #SqlAgentSignatures
  values
  ('sp_dump_dtstasklog',
0x7E78A58D20216CAF9824FE20BA55ED6D5CA4E652756EDCCFD7BE49F4D2A1E16817E4D3836D92E33D1BA198195ACFCC088D7E92E01852A7CE55136C6296901C556ECF32612AA0C36DCCCDDFD8BE81E0762D21517439FB2F23D20BAF005BEC50EA577E8B30711740639A624D524BF25075B1D0267D7B084E6AB7DEF0754F133435)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enlist_tsx',
0xF4269241A8557AC211649C4EBBC58910F2A7FC11B44265998CE3D5A86FE9E0BF8D421776091BF9AACB4F7D8BE1D4682BCCE8D6ACFE2F158D1BF0DC2E11FAC9E98921334D89420815F2B1321F36C67D493BC2E2C81CBFBAED81F2700014F80979000B0DB20578ED6913150875A82797D91AA4C2E3B9D110D3D2FEE0BD39278480)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_dtscategories',
0x2CD855CDE96FD8E102B77E2A406D96606B7C6CD692EE08B7876D284BD4713FAE5C14E5870F87933330C2D82E6D11AF80F155B785D259A98B1CEBFE84E99501CF72C1B75F6BCD228B1E8B2C1216299E1CCE83B29326824C5478D76C35132BC611662911A7ACB2C4EFB03BFA54F20DCE238BA44C174F611B0AC8DEE0A937743F1D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_dtspackagelog',
0x0CC4691067EA8DA0BCCC42F81FCA6BD5175DC15EE2855AC880BF7CC60174DD0A64D5B8CB9D1D525FC707A069C9BFEC383240320B9C20A8E017187352E91F51C72CE3ED156A3249CBCD2C2F9A30F2F5D2F6B9D44C0E9E6353CDD4BA9D6042FD8384C50CE7347725EABB1663652181C62B561A7CFAE12D65077DFFAFC9C677E515)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_dtspackages',
0x986E459229FD0E5FA139E480D1360435FE0B20430D8C852AE45C3EE700779963E02B715622553157FD56450BDD7101EC0320221E21A3C6199EFC6023F3BB5AEFA21CC98C6C5DE1A95CE6DE32003A07494CD9D3E4CEC5DDCB9122C466A909E79719CB61269A8B80B4037E930A729D54CC55E527871C1E5E3FCD725D1CE7659F4C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_dtssteplog',
0x603759365B2F834A58443FB3F714374AEAFBBCA16EF8E95A54C439CC1575B3B74AF64A97FCA602E5C6E4B70AF98DA88E6B03CC9B4C344C171A1BBEB6D9E51EF7D62BFA7B1332BF98DC1B48DAD0EBD2FE8CB607A7800BEB4D36AF3985293CCDE16450AE31C61C15F1EB7F0A07ABC87FF54758513CD597EF4B7CA283DFF463F8A3)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_dtstasklog',
0x2D80A04620DC2D962EF655C5DD753A6F9B0AE4E6D50E62E74C35DA0C8398D542282E4AEBBC8361A529786F76957E448F69F0A620935A04DA7AF3C8BB0071F3D14447011688B89BEC9CFF5264EF5FD37B30694070147C9F7F3D3C51EBF59432725B21D02F7B92C214D0D51B56A9F4DEB7C4AAF3FC70E31CF3523E4136D1B3B6A7)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_login_for_proxy',
0x470C93793FC91D1675699C72E4AF2E96CBBAEE14C7A5ABFDB4B15A5231035BB2B6F192BEAFD8D4F7D9AED276F90918A27C019695FB50E1ABFBF4EAF460ED9AE1CDDF03EC320E9C9C1C838883BDEEA502DD4D5530A8D0D909C94A2ADB73E98A795853D66EA6B26CB2F980F0164430495ED5D3C81AE6006EA68D7E1AC6E3893B4C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_proxy_for_subsystem',
0x5D977E0766E3AA5B59E0D3ACF9D8F0913935C216C1056732347CC4CCE8D0624F8549E453A2500D8D8C5448553C30405EACC315287B78C43E45FBE3218DB624A12EFEF14B5B3777E5F6521FF2FB5C241BFD4FA5E7370AE82DCD3C511A43260B801B5938D767F3F9FFB040BA63BEDED2C7DF0FAFAEE9E51AB801B1E4DD9C56920C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_sqlagent_subsystems',
0xA7D30B495DE0FCA655AA56C2B7266DEC51CE6DB5184BB425E5BE1DA82ADBBD16F6CDF0609182274309B1C810ACF7AC1BD2F0B9DE02DF423EED3275FF0D500E2C6A3F1F60DCA9348BF06FE78B7A7FE6FC39C0FF33BF2A2D2615858F3FF993DC6E158A5E5D50708E8F9AF6D3433354BF9250E9C97F207BDEC06519BBB2AE781696)
 
  insert into #SqlAgentSignatures
  values
  ('sp_enum_sqlagent_subsystems_internal',
0xB1F4D2D71E93C1F36EAC30BFABFB104A871FF48EB5EE3CC2EBC127DCD9444764309E9A6C365AC3C834B897D7006EFEB3A4F5A7E4D6D8601968147A119623C585FE7A3188E14F62AD94C6D436B1C23D0AB9D8136A39D9E9C557279AD5A264D08080E2D0B592E1CE58C91BE9D1F6E741122ED8C153F57C31F7BB9067A9DD03C542)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ExternalMailQueueListener',
0x5785E6CA3DF7955BF27F00B2784C13BBC2593D246CC6C30B7B06F89C79B321C73977612B80B04047248011860CF0F617E98F29A7D928CA8D73FCA40094353CD82310C879FDAC8738AC68DCD0C1928AA4AAF5B5B216CE3658DF71F383897B42BC744716C500D866CE641290295AC833457DA225D12444F4F99045EEE98A3DD38F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_generate_server_description',
0xF54EE92DE6DD33C2652C4F8B8CF242586B33074B15E5978341123594EF163971ECD594A6E38BDF4BF7EEA79C761AD98EBD8856188C934DC653A099C6A38869575DC9E12E36CA02F954E26A8631F114CE62D565E78E8CA0FE001A0A3F642D022B25432313ADDAA49E1FBC73CD8DED79534450F3A1AC57E18C42D0A21D354A0BBD)
 
  insert into #SqlAgentSignatures
  values
  ('sp_generate_target_server_job_assignment_sql',
0x90E3146D7D3A3F4CB170AC09BA936F78A0B07410B16CF46A1263D6F6FD01221894157DE1E3EF3E03DD57618F65E2971158C963D07D845F6061B6510F18CE6ADD9ECFB6589A373D703F0D11274B5495D44178D3080624050F5AF9691B74BA7B634CBF6BC03C701AB9AC7521E551515F444157565A102AF1384C2EBB3EF2E8AC14)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_chunked_jobstep_params',
0x11520B2E6E383F63C448E88D97BCDBA486F9135D49B0EFFD3077C1665C92AA524178E0C9701D428102F3F936FEF3B478D046BBE990F88349F7ABDD8983FF72B0F2CFA72F056C5EB2C307A644EACD1836B5CB394BD5AB44FFD93C40FAF78A883C435831EBDE996EA207AF504C3A9A409C49787E913FEAF0A733765A39158D69AB)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_composite_job_info',
0x831C1E526E5BC5F05814552157D03BE13034765126780D9B4BD4C7367F99525DAB902BDDDBFE75958BF03E22E1088FA8AFA9EB0450990CCFBF1D159BD1848B692BA001F0117372C713B754E0807898678A82A1E88AD17EDF4DBE4038BB73ECAFB92EEED992BFB50BB3515C9E471716230962EFC46C5CF913E7B06F8760D0250C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_dtspackage',
0xDF500B300B3076953844DB2296ACC8BE4C0E726559468F989180DA2BE0D54C28880416143E9DB9E3E99BE642DF5406866D0D0139B6A7BD2F37F07B3C24E57AB6DD98140D63F8D374733AD42DA74451AC1A136AF5DA957B0E824E533B31E8130291A3671C6608C49B5718199C7ABB02C69F1EC939425C2AA9BFB6614628758178)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_dtsversion',
0xB17C93FAE7237A377892D4240F4A9D3DB960878269665C95FA67BD9B14B17BE2F6ABA21D17E4E11C9F4606445B60C7C40100F07587DDBD5BBAA07A530172FE9BBD4E721D02099E61A299DE905EAD7D7104A76FDA6E099A5A1ED8280E2D2A5850954F03D6B758935237D25A913DB82CDC579B1B8844CCF04DD39E217BAE393610)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_job_alerts',
0x17D178373DFC76571A8D8DB389798D24F6391B33392F47941832F039C3CFCEA3680496027DC15026165F268B8C45CDF4D8A4C3142ECF4E6DA46BB6F2DDA6D487018F51285CDD6ABB38771CB875EDF2CA83764CD6F9540A3AEEA91A79478B6272995B714FD39C07612053568FCCEAF7FAAD726596C363A2E8F2A5EFA55A0CE73A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_jobstep_db_username',
0x347ACFC68FEE5970461E521B8A393813B924F83B83779D509B621F27EB262CBEEA8DC7EE81F3E22490F80C246D08BC6D97DDCA2692B757C908EA719BB322B42AC61C9947935CEC01033F169F760B33E5595B9738ABA9DF3E31AEB84B6013E4C0CE7C036354E3DCE7BD7BFA9FFF1DB085C1B1BCBCFA1D3034457B6838D1E5BC80)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_log_shipping_monitor_info',
0x1A1B37BDD7F5503BBC67A96856473A7EC0720DB3F316EA42E8C2B0D6A83E1121025DA6A4C75E15D94C653CF7E27565B57FB276D7C8940C2AB60848779E94821D367F7400C50CD4154B57138A2E8C59E3BED3E0E3E48A9B1E03D2F342FADF7375BE53855D707E592A319FA05E30BCBA93CA12868E43AB2520982776A1424B3642)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_message_description',
0x2E29E9E800A808C470EC1788ABD9CDBFE6663257C735D1F32DA53F99D61EF3A14BFC5E35F3ED6A0A18DD8F5116E53978765AC38B1A462DD617E5384F697F9FCD5DA21613D65DDBB5CFDD3814CF5B45093632455E601122779E653D655A5FAF3D167EA5F16C14F79427D6DEA3DAE2D3E2D2650947F92073B343FEECEE1C9FE700)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_schedule_description',
0xB08B3751DAF7E440915C13422030EC72809FED266B72D07057FCA223507FCB30E80C91AEBB8AED59F54F1E280A28E89143EA088B745AB4FFF6CD9D6709297D3D5016862BCD05476677E74369579783328FCCD5E031B94567C9F29E194F3CF275F2945F1DBCE4785362D3FF823978E8E5C27AB83AA4EBA80CE9A4AC129B196020)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_script',
0xA789BAA0AC2B822275F0E3F69C044AF6C7797E621B51F476C2EC2CCAAF822A779F609673916C5E46A477C4332AFB885168436893D0D9FB15EA1A5D76CF3319FE9AD239CF2D881629CF2516813EECB4C621356379F863A39E7FF07C16B961DE795212BA21B100218FDE54C3E0AE4E964F597801E4696AAA2B2BB0D940320ED60B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_get_sqlagent_properties',
0xF440FF72D7E1E7BE14EA52B1FADBFA89F66F3006FF7ECC6A04BBDE53196D9809D53B2299C283FBC95B26B217A2935300A2E4FDD33F309099A3F841288907AFC477139244CDD411EA817CB739E445E16B019A603A6BF3399469A345AB22CEBBB6B7F72955511C3C7ECBD2BF5199DE39A2C535A861FA209BCE452F5C20A70B0D18)
 
  insert into #SqlAgentSignatures
  values
  ('sp_GetAttachmentData',
0x47535DABDDD2927A0566E47BF957A4DF9909A72383EA50B5C39D3402E988D2A08A0C64F1EAA2BBFB18994C8FEA8C24A6551DCA2414662662703FD02B398814AA7EFB1351425E9FB67B5323DFAAF065DC3D83D96FEC4504BFAF75609CB0E3C87D90B72683CB58DEF28B283351F820485B7138A6FC59E72604D7B26FFA80230D7E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_grant_login_to_proxy',
0x34126984E1A10BB02D8CD0FD242486163860C63A0988C03CA6545ACBF2D9F2D72F1E89BB443F6EC608019E1F07F1BFF19942EAFD1631B6E3BB7C78BFB57BBCFAAAF3CCF93ACFF1D00F316BE589837F17523195C545021BE77239C1399349B18B5EFE026AF0249BCB0375998DBADDA3A7DADE3BDAECF251388095D173A90D272F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_grant_proxy_to_subsystem',
0x7E92A2F48C6E931F006B1EC079B73974525F953B17D6F5FBECF886B6CB04ABE7EBDE7C90CBA07F39A7FC64957F43C36EE1667339ACD1BD3D0849B3297A36A128D6A0611B29B05E794FAA56B11E795B965F1B799C09B52542F9B74AF22DE50B28F745771332B9C91060055A281F53AAB8D4AA7A6E28AD94DBDCC934FEB557367B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_alert',
0xA7E1DD4EB19B316CECAE549B5067B5AF1BE7D2963E0055694838C9144F94B743FF964226EB1B48BAA970DFD33362EDC7EB891AF14D6E6C1B5C679A0081BE9D139006E381AD87753EDE6C652F5E2068873786152EFA6EE1B63377230E36E82AD65EBB948EA4DCBC29D2747CBC900D9792CE42F7D7E62BF20047078A9F48A03940)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_category',
0xB87E2CAE4F68774299E3D7645F38933364CE72E852168D707D3784B86722C90E20C0732741AC7E9D4933B831B87923163991E03F99F531DDFBBA8A89E9AF8049AF2EFE6FBCAA470691BE2349B9F68AAA8636EF8BCD0857036601FDC6AA173AECFF994FE24903B1FA064ADF78D8032501E02AF0698005AB00D02583D1A0CC63C1)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_downloadlist',
0x9843165EA302DFF6001F2C12C6550EAC12F75BCE27D324422D5F24F8F41DC9C9E4FE78DB05C0A4FBDDFE45829D5D9C4C710D0751F122AF0D7537E3C6A8B60D3162F5500771FCAEDA11DF9441A51845CDCE474CCCEBD4A45233146AD32274A9AB1C60E0D960373A8B3C3E5D0CD2D55575BDFB815BDDB7C970960BF9F02E3482A9)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_job',
0xAF9C6D44F4A6BEB576911D2CB24C70F86DE5E429407223B771CDA6BB0EE48C6AF19732B7C4EBE684F3DD80CD857CE22580C945BB7F8D77CC37DDA62BDEC787B7D6EB36432649388E04A553918666CD5B71ECCD7BDACEB7772838837E977338F746AA930EBAC4758248B362CBEEA9A37552CC20A1D4F95441582B217C0D33E1AA)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobactivity',
0x5725AB4A1B938EF54B763643EA7EB8DC007E25D0000E65AAA6D78A21D400A0DCA1F1D31A36AB01174113DC58846FCFB50F835287117AA83B8D7BD99B1A76E58EF5634901B61C0C697613CC6C5FE5C88E8A46E5C1CC6A599501CD423214157A30C063C0C84B590F678387F1FC3EBBD03A2BD511FDA5023A47EEA8FC2318A1E247)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobcount',
0x61CCA5D036C5943837454B14B204EC349C91614EFA21FD6DD5F2A631261D6796591DFCAEA67CF4216A72B9A01819A9D00A190CFD5DE7B457EBC21B1C6A66C507A32EC08806AC75B48C0D87440DCA897F1A046B66F9C17DCE5197177D8CF96369A5FAB0ABB2AF26FCE04BEBF91AF79897928343907B1ED2CDCCBF3CEA21530FA6)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobhistory',
0xD55861974BD841FDA5FBA4A59C3A8303FF855A3CD4CC54DE6E8C8C7C5BB4BA6D776686A6C3A887A638EEAF3EF918DBE2AF6E78DEDCA4177BF073972E649D08FFA20CEEC63F0DED67260B91A873BE2FC612FC2C89DB0CC7BF54E0F5837AB147F63A12D31201805E93F93101AB241137C114DE6A6128CFB43F18C121308FF39E2D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobhistory_full',
0xC7A6F5277B78DAAC2ED12F99E9537B905944B6CC5738B4FBD1BE55AD4F84FA440A62447C479105333D20ACB946B9BCC07CB56DE9F3DD21CED013D16DB79225E16AC6CF6FB0BE4B6C52A8B52691D8B2D48ABDFEAB60D05A034E42A6007582F70EF9DF85DEF692F36D1C9D70ACC0A4A9A3D9872B1D1E292ACA6AB5FEE9F5CBD55B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobhistory_sem',
0x51C2F4461435FB61B7F6ACE28D70077CC058CB0219C0F16AA65CE7B95FE722DF2B02DCE8DDA57D576F08C4CD7D356F2BEBAD7B01FD94CFB04D98A926E8F6EFD1DE375188228C2BDFBC642FA835450BBB711D0845EEA0D1C2A7660B18753470FFE1771BFEA415ED81FFCEBFC49900BC4CA49A2D19075D661DD8B00EFA31AAFB2B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobhistory_summary',
0x939B4B30966C575403D51D28AD639A3EF099711BFCB08F6E295788A599CAF95241997BD34FC2A01776C4917C14E699F55B43C812A0F677288B9D8022790440043F1A9074DA8E6DC5C1BF96CF376E6D0F7802AA1FD3FE6C20A39BF3CCD3CDE4A58706BB4C965C2D665C53960770C647F540F9FFC845EDF40B27CACDF2A232E730)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobs_in_schedule',
0x952CFA53334AB01B8064FBB1A2159C33DAD8BD39809FF7D02E7DE1762EFBE58FDA8284567282818380948134F6D5E28F6909AE18FBADB188BE0AF6605B763B0E1F87FA55B4FD55FEF0301F5ED6662CDA52440378770FC1F8086A44159CC3166DBCBB55BB310442258FFB863D5F1C9D5D68654D0CF15210994C52DC2C86CE87AB)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobschedule',
0x632127231BB585EDB9C0C574FEC7F6C838A87AD682052F49AFE839C120F0E291AE544D3017B4805C7D271A507A43E8FC46847EB92C8FA6C55ABE9355A059219985EF58C0CBECF6D8D8E6ABED96D62CBB9F74CDBB4B348808759E103BB307604FA564ADDE4ABCF505B8F4F769F2A78DED259B0FAC98E7BE41EE91017F6B5C2A19)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobserver',
0x00738B366484A1A75E4DA3C445F9D1C9AE5A535648ED279514425D5FBC565895770EA4E2442C4614352B4D98515DCD37406E4B6E67F640AC5CBA3FBE8886EB0F98EAEC30CFA6BEC3138BDDEAB2E0A44B8AA3A814E4FD4C45C0C97E8012DC157E699EBFF04E652FBF12D5BC755CCC237D9094417A23A81050B6A7C055861CC69F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobstep',
0xDDF8ECD5428350475D120AD3836222A8805244777D847322DC9C6F48EBA33EE56CBCDB706C9070E23716DD066C64979CD917F86827C28F3539DEFE547A3B11BF8B4A3DB08C534C14DB962EC06D2F695E2CBBBFFC5B6060F5845B729B875837F9F7C7673314CAA9CDB5B6CADF0BD5B7606AB541E76862E9EC80A3A369C5EA4C2B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_jobsteplog',
0x6CBA25C3CA3C93AD59D27902261CD2D5C199C9DEDF925CB39F0B99B70022330F9429DE0D55B5FE35892A3F6B40D3D36BFC7EE5B69CEA8D830730C0DCE64EB87B3BA9221B496A8DA833A58CF76E25D6DACC442CFEB7F8F26651E0EEE5B1503711899F70EECCFDB2973BC5343A5A74B3937E7C55B28F3E32AB61CF829CF394885F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_maintenance_plan',
0xF35075711EFDDDB5F6483078623C5993EA2CD53778E59BEB7273754465B7F11D9676817FF34302EC6C6F28E42F17E7B0CA6D156EA357BF7A65358BE05CCFF6E46AE16B860E33C14CFB4DDD06C2DA68CC9B189B29A47C8FB6B01FA2314D27AB49A9A5B388CD7104214EABD905F688176ADA6BBA3594612B6D1B34E865E330281E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_notification',
0x266D5D893C0602514B137D3B9E4FA088A1A13A54B7F6EDDB4E6CC4476254BC5789DFCEE192431AB4293C34AFACE204E6D27B4DD36DC69FD2E02283EEB2F18B067B0610C5DB5C4BD8261D97D98A2861BA14B738122C56AE7123A139D7E94CB4D1F14B89F6F6E32DF4E5C96D30A925E027E93DA68F08EB43F829DA87B9F1F8F1BC)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_operator',
0x9E902DF931267A54046D536C9C7BD5EC109645B190EC91EBB957C47FF4EC9B230882384123AFA494C5D4820F21C77235C7422CDF5B0D9CDC6867290008F873A207D14EA360D75C26483FF1EE571E572E7A7A79C058C1B7E17D7BEC18F2C8E9D099D37EA4D0166BA42D6BDB6FCA77CB746DE91CCCBBB325D1885BA04B6D216860)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_operator_jobs',
0x628AF77CA9499A116D659245D5E4512A6D1A75BD596BAAC80AD970EF222E94ACEC0EAC8D97A202DDD9E09AEE5E11117C4F759D39C9303371282F577CDB62761498D05B7C6482A767A42A466A59EAC7A414AFA955CACFE5C3123ED073E095E67C9372E9A797D8E9D670B09A38D42AF72E8A0DA7CC7BFD75F830DCB2A3FDC7A744)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_proxy',
0x401FA83DCE075D8F247DEF9A233E8D5ED1E51DE1EC4126B5847C0326030664412FD107CFBB3B41AAADBE5BCC0D48B884F07D411633F85D3C5AA45C180AF82C2DADE710E89B9A281009DDD36725E4D931EC2370F58C8A3CC5A46FC5926295A94716F9EC8A74B822690C53586A8C5A4E419D31E1B610126DE97D61F6B42F06D741)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_schedule',
0x50CE9AD6B187C9719056A988C034FCB0266854CABA8002141A78A0D60F5DCE765376EAAADE97950211551FD0A9E88676CADFBD04DEEDB4EF2EC36620C8947CFC64B7F45B7A444EE3FE3F2B840F9E13ADBF2CD1687E09BF86F3C636E5EE0DE8B569F4A8678003BDF4F0263960231D340B1A39E248B90CBBC5863BEE0ECE4A95A6)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_targetserver',
0xFB6C5D0A1065A13CE90AF8FE09664E2708E1FAA5C105539D96E974AC0C4F8ED279DAF2422B435A6BA158B2537E3D1AE4D3DC110424E72DA66829E324006FC2E34B5CC473628B8E552C9A81EFF492BE12D33E269E952079108B7CF1CCD9FA2129E23C219DE56DEA77610CDB8D6A9FD454359561A2D7E5F4140BD0C890BAC8216F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_help_targetservergroup',
0xD2175F169A9A04561C01FE1EF08FF003EC1B932239696EC5FE41EDD950887DD6DCCA69397B1E5AF6EC20A2F12FF566985A4094AD7508FE5D9C3D186EF79A12949934897D96CF33C399D0ACF29F538E9ED10D0D063A3D9BCDD444E2C50BA8BC38E7D66DC3AB33D5F74455C0B9B5FF4C85D2E3219641973A0ECAEA8A56A03D03A9)
 
  insert into #SqlAgentSignatures
  values
  ('sp_is_sqlagent_starting',
0xA3C8C09FC4847D49B8205C9EDCDD76D679474BAF0C5FAE96A64530AC19D401407715AFACFF44EE9621B631948C87CA7D182966E221E073E43D28EF06764D3914E539E566BF938E9917FD60CE499CFA7F8F155D5263F9D9B0E5F71F21D83153FDF19457B1A6E0C3B3F83E48F288C26074BD523B2156AC0F0A1BEB83506DFD8C5F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_isprohibited',
0x199CBBA5EA4CEB9F3F0B8981DD4148587D1EADFF8460D4873F0EDDD3E164650C1CF27D148A09FA428E530AF1039549A8D9AE523B235125841B2B0DFD8BA5434766ABAC1725A34B3D247932B06255E9AF015B94CE653EA63E9E28F1FBC090CA2C010E470632A95F4D1E2716340FC8D5097C62651A76CD273709956B9F34E0921C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_jobhistory_row_limiter',
0x0FA6AF4AC1D3B9C5E353B6650913FA2251CF9C030D3A26422C70041B60C0C4ECF4AE9DB47276809A636077576D3CF5DF1B972ACC490FE1B87B2EC86B217D494A329D9707ACA8FB528EDE8927547DF7F235962CD35EF0128449BFDCA2A19FA12A2DCA4A05BDDD0403BB8C54DC6FB20542059D4C2F23BF78F4DC47F72F4B32606D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_dtspackage_begin',
0x91234491B06FA83C39008E10727FD8507E9678F35088814021451D060EE3F947B4C1BE180F7783B2BC34AFD56D6CBE0D372B5F3A0AF3DC4BD4B23D8E783EE57B18E68F1FE609C6EC724F535EDBC7943BD163CB950192C0FA62A05CEB913BE6E159E4D9227FDCFA8B7B14AAAAA11FCFE31A5521D08ABF018284416B1BC5BEEA1D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_dtspackage_end',
0x8937C36EEA1D0E7EBE8469B4703B846541911903C7F2A7F0F9EC90241BA1CC5B532F347882313906D30314760B6E223C2DC77F0A3EF7E0385DACAFD0A260C234B98CDA8DFDA563E09234E029D300F5A3346441B0FEEEE43E7B04399506D8A19E6037B267267845709E03805665A0CB2E1832BBD9EBD73B8F071197248DC0CF46)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_dtsstep_begin',
0x09360DC3A17B58CEDCBA6D32F30201DA23E74C367E567EC2583FD89FF8E7C1635586374BB88439D4750F9B9A876E204F31818FAF061D89087C5554AC6527CD78D677E5DB904ABBE01C7F6608A6EE050FD87D612603537B81F43E95517D55B1C83324953762F31E4076D213DFA4B208FD9ADCABCD6B4F1297A7E6CAECDE6CB6B3)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_dtsstep_end',
0x13F5893E92AFA57E9549F3047C0DCAE7C5A6473075A78CDFA0A628CD3DC075AE561BF1C5BC91FD25CA57C76BB2087489D061A1B9B64C2A0DC9EE9BDB55E5923149458D7F31C39AFA7D618C4F6D8C0B547491AAFA3B4239B33EB9212EA6AAD8E0AB6009EA489A82E98294A8CC6E87241364A77C244D14A12B66F15BDB7EF2954B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_dtstask',
0xA212ECFD68C97B10A9EA02E1474597FB3B8EA21A00621D4F6857632262604E60AE24266C10B4115DAB290E589224B052F1970A678B80855F2E6E3FE92A949D8ED80EBD73C664BA6B67D8D06FACC3B71BCFC0C3CCBE211467723A8A96416B1D86659C87D4C01105B33D6A39FD48D856E2F9005480580FD48500C98C1DE9FCA9A1)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_shipping_get_date_from_file',
0x7F21D1AAEDF597CD2CCE8C25BE94C48F8A9A47A388967B2461480EB40FC068B9004292C4BF23A7368B5C4562FFFCF06D73906A4FECF3C8BE7FBD9E502ACCB47D1D167FBF002CAB1E2AE5EE4547046B9585BB50B4E2DFA37B05477A93528EDC70EF136BBAD87994C26FFACB9DC722B75DA623A753D2E93534AAE58729CA2A1C11)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_shipping_in_sync',
0xE65DACAE2A9650D687F85F6E3C13AAB41DFE5F34EAB2B5E7113E246F20632025E6652EA78068342BE58C2DB2E17D782ECC6579796285C0B3861714939CD991585B1B5D046ECD55F446E79F1E9BE87497F8517B3760C3413CB9592A031AB7225E285E2B64D79F80CEFF72BDD663BEECE34DD38B81574967FB6F0559D03B8179A4)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_shipping_monitor_backup',
0xFFA6D5AF53D7F9E000B1798E76C36FCB136A36AB49A7F0C7F954EFA2BC53148C23726FE99BBB5E596BF71733471F94A5AF07C758746168599F2E4CCA8183EB480C04D0A1F6C3A12E6DC0FA8847432BB12DC44451CE1E7515F4CDB1F48CE8913BDBDFD58D43473C8253D9B97DCCA0DC606A8B206B07C1554F8D3A172938A39E8E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_log_shipping_monitor_restore',
0x519EA9DD89305B3FAEAF94F8DB63FBC91DC6D06C550DB72C54BDA1D8D34903F932C9CCEB7925E410F0F8CCC177606DC2143D8F24EBA15636BF707001BE44F5148E3FA6FCF42798C78E5F63BC33EFA881FACEADA762B8858849C8F4D930B8602699599930365332E6C51EBAF8E5ED1499639562DEB833D7EFE496E86DDE8F0E8B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_MailItemResultSets',
0xA17879F882250A367D152BF0E1063C4AF2C64F0E1D80E0C68AB68649BB827C6E225901AA8079C4B81CEEF8D8C473FD879DA06D63FDE94861B524FABF2947ACAED2057FC99E786C03F34B5C17A4B5AEFCD75B0ACF3A7F43DD132AC34402DE766232AA65DCCBCAD92CBF46B36C1B3EAA75CCC7EC5CA581439C407CE38224090220)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_close_logentry',
0x613F51352FDC5EC50A7419A5260E25A9F086D00807C92551F5871AFCB473C330A4E86542B8EC30C7C6BB755A5645CC52FC45AF93CD78209B8B8931C105BCD76CBD134BFDD318A2DB165D87542E0B6761CAC330F5A24D1BC0014BE8FB2D999FB0383E906EC434F60DB4B2B2C83FAE49899AC7DCF7FEF1B56453160B446D444574)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_delete_log',
0x88478007465D3EA1A1F72B10E07A0F6C511F1DD6CEC7CCEAB60F7C683B62B1F0B041821AAD2A49B95E655E6893814A15BB49E36ABD581868CDAF24846C92AA1CB782A338B3BEF1CAB028CCACDAB783130A49B48098249EB718E061A3C6F13E43262C2F081D5CF8EFD5ECD848EA214EB0F70C92F9A3AFB2C4EB73ED92D0C0CD69)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_delete_plan',
0x7A1A5C60513554D90A7349933600712B4A3EB67C0761DDBC673235F6BCB4994F7284DAE44C9044700605A61058967F5E2F3DE48EA3EB9357BF2A65C0B55E628DE1858BFC0BF08934CF1D8C075C9E8F6C2950554C280942AB5AEE9911BA902CE57846619A8938320131CBA19D7ADDAD958444AE8A66F1DE006BE02E285E7FC6A8)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_delete_subplan',
0x7DAF495116ED5B794157C652028A8B36736E08CDB83561E4B4D6C6F62A4238C260557739A76CB6E52F42A2A60BC49464A80E4746FD4FED4B5265939053227E0894138AEA5F29F7F30DA339AC44006BD21A906DBF9DA8CB356275BE39C695CF025C8EA7898A9C170998B9A4EB36F14E519E9D7F8275A437742A5D570740E4C5B5)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_open_logentry',
0x82126022FB3ACBE202AA53016B96E8CBFFE14251D82357917472DF17289DFD67C36D0448ACCCE8D3DB8F69B1A40DFA0CB4B038E9435A60428E241D38E8A45B5D0C6EB782EE4A943DD13B3B27666F512C19C858E93CF5275BB739DDB64904FD962A514A35D37F7A91AB7CDE90ECEA234ECDBAAC061A341819D075473C406C3F07)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_start',
0xC9D6C97C423D6EA076DEC70D7149281D00C75345B7F8FD810CB455AE343E243A68262A7C67CFDC8F8D13584BC26E58BD141C2A62215822CE6E0B43FAEA5C1F15F512272966DA00CD73168C3AC9B08763A8968905AC4709FC541E84CF38121DFC10E01DA61DE8F89BD3C4937901390582C874D1606C8B703BB1EF098B253D9A6F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_subplans_by_job',
0x08C91CBCDE1B559B9370EDD5147FB3AED0F1C1BEEF28AF57401B23A76923E0DD541DD37E522486F77599EE2E2E9B29B66887E33FC5F521520AC5A079339B43F30AA21B89685A4320FED181EF476661BEC48B94E3BF9BE8CF35F339F564D5475191FD641BD431E0780D3BB8865C2B1C8A8C99F7CDC4B81B874129A19EBABDDEB4)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_update_log',
0xA1CACA2B3AE9A86B8DF8815FCA1B7F20E4D51CC6DAA0F0F74F45FE4707788780353184E60BCFA1616C4A80A90571BD2C0779239F8BD5AF1207258638DABFA4BACD670E867C2E226DF925D48C4830F3A3BEDFD2002E3B232CA7BF13C9AE79E95823C5509D0F54D64379D7A76E598E32F8FC2B2BDEC5F4E992E8AD04673F979603)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_update_subplan',
0x716A7B861FE757EAAC82C5A37ABE5B65124831EAAA760BB4D3FEE738C2249B02072BE6BE7C635BD5839C9CBDBCF83CDFEA383A4B2EFFB0301780B61B5BA143DB6AE777A12183A07014706F3ACB2A213D2FE12E770CAE028AFEE843BA8A9D479B8B649FF028EA87EB7FF914A34ABB07AC576C91EA0723052F5190EBB8C5E90D3C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_maintplan_update_subplan_tsx',
0x323C696847CDBC85FB5BA7428C8CD15EAFB8B17DE2866A1DE4FF2DCB474BB74509523414B1383C8F587A559F2D488AED816366132F488AB7C838F6495F05D8ED3AED90491FF2DA5A401791101021BF2DF1A5B0DBABCC421B83669BCB862671400D0B983B113DFE25DD0DE4E3492058EA46E0FBB8B2E4E5FB4130AEDAA2FCFBAC)
 
  insert into #SqlAgentSignatures
  values
  ('sp_make_dtspackagename',
0xB894CDA426F6F6A02EF0AFF4E9705C94DEB896FAB9DAAA81078C76A7B950D2389F4D4339F0F484EE9F303CD6A0E16D0AB5A038E747B3F108A5A63F3779583BC11F3ADD78E39D71155CB8F9B0B0E179976B3163C24BD411174AAA1EB8080EFA8EBB62704A70819BA11E436EC2303B90E9DDEAAC8845922985A6103A8A3D6893C2)
 
  insert into #SqlAgentSignatures
  values
  ('sp_manage_jobs_by_login',
0x19A91FD4017640FDA8A6997E1418D71030B468A64381C3FAEFD1D6CFCC8F72C8418BCECEA8B939D798204E2A315B2C57C74FE4554D34C086E285727CBEEFBA562DDE08FF9FB726D7638BF1FD1C6C6E77CFE2364C450F0317E3A566348BD5FC588C871FAE018B8AD9E446B882C2DAA62A4D499C15CB325C92EAA69FCE5C76C352)
 
  insert into #SqlAgentSignatures
  values
  ('sp_modify_dtscategory',
0xB3B9475CF852D3087B66A76BDF1605A1FF86F34C6C70411D8695F52AEE80B5CF67A6E28EBA7633FFAB5CDCF8233249680078829DEB39C6F3F279C162680386E26D70F007797920DC6B13C7E8CE0E0B8AE591522335C34487609764545D918826FEB21A7B38C74A90C206BC8053D676A5278DC27C16340EEEE95AEFC228A0BF3E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_msx_defect',
0x3102858F3A8908D8E1C0ED2268A6131A25FC56DAEBB90BB80B1E30D5E204705086A771B392EA3ADEC7880356213868DC663B731DC31944BC6EC9D5A7F59C480C3A691819B5FFC08C771D53D68CCC5355330A989E94F3808FB6DCAF3CF3B0497167F8F7ED8C6FF511204BCD7B84BAE9B70EBCD6464E2DA5036744F376648B2112)
 
  insert into #SqlAgentSignatures
  values
  ('sp_msx_enlist',
0x4832C75C9D6CF5B3AE0510959E67FA148682A46D09417A78EC18783A8BCF8B3204A85F14FC4B15CEAF6A3D8B9745815024AA0BAE3D5352A0E947124D3ECEFC2511D6F283695CF2B31B54DED0E74686DA432D4ED3FE2F7086199B2649FC6E856176B1A8A07F01D78D029B768B005B4DB00B46BF598EEFAFF761576A7225459B2B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_msx_get_account',
0x92CCC2E763289A0617478FADC4D8B4E71FDE661D827FFAE22C40A2EFBB369E6C2AB5CE54ACB037959F5712AB6B4219050D9DBE3ED82B5F33D0C34329AB290A485144308D44190D6C4AA4A5AF2ECAFEDA9577B11162AE426C1D9E0FFD413BE104245C83A678F4FCE9152E311FC39D9B625E998FE373884062BFA8CFED15590710)
 
  insert into #SqlAgentSignatures
  values
  ('sp_msx_set_account',
0xE845C24689AFB65163020697B30D954BA3C3317048B9E397F1700890F2104081C43E69D808AB5B5C5118D15641CA04A5EFD74EC80708EDF4D055E7953D07DFD9A9634611D4127518E5B793A1C0370BF6A113D4EA7A38792BF06F3EEAA244B4D540DE3FF1095901DEE894EADEA338492CF9BAA3E536BEEF9F691506893616BC65)
 
  insert into #SqlAgentSignatures
  values
  ('sp_multi_server_job_summary',
0xFC716F297E38D4825D77106A7CDAA3AF79D44F427D19025AC913E945B4D3A2754B194E2A64B6DDB548F4FB1EF9221319E50647DC69C06093700AEA37867E1625CFCA838178CCA3DDE4836F49C32097D68D519B815D81FE3F70807287B990288F61D216AA59F27646C3A8D655367D98E628492FF42E1B4F3D2BA7C345BECA5A14)
 
  insert into #SqlAgentSignatures
  values
  ('sp_notify_operator',
0xCD97CC41246FA71836E2764DA9EBC5B27681F49F74C12C14F3D59A7DA75F05D5062168EC5ABC2D4A1FE9E34731293C458B55704077634D5889F6EEAF9AD95E962FDF7DCC5D9C0FB242E79E88D7D7B406B7E544665F42773757A02CFA7F7B67A329632D302498F5D05132082AEDF02398B6B859B9EF7CA9CD0C864918254C715D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_post_msx_operation',
0x5F1952FFC58E550016C5C0850D82AB378D063D7C06AC822FB3565374ED014306D25B95F756033C3DF98CE64955EB592D76BD99D35B4130357028551CFE23D700DFDA75E085BA680B4DCB9A7C4C6F47E26C85442BEFDB51E1A179B1BC3E25DAF3662F4BEA0ECD17DE3E4A165328E6399901145AD645B016C8396004849AD3BB47)
 
  insert into #SqlAgentSignatures
  values
  ('sp_process_DialogTimer',
0xB3EA098FA0E928A33BE1EF696F1C4BFBFB13CB0D3CAF75BFF774D24C87118D3A087B454E2C51B9403F36F79965B24DCB7EF125441227813C13C3BEB0C1FACD7E7FFB834115B4D58FAF3F4686CC4D561D629329405C8ABE07834312BBF1121A3F05FF265F9E835EB43CE65FA70222630E06D98ED77497B1D5A0046FA6E8EE51BE)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ProcessResponse',
0xC66875653EE7F51CCD185CD7F597BBD8B0DE0E0DC8577B5AC25E30996DA08F64076C16A8F4CE1D2E871516F24FD6369157DBB5CFE38ABE09CE3C6E0A2F3D978767991737F66D4DF0B1FECAF57C497402307F9E4DC2A96F601F9047707F5313EAD20085904B2F6C74FF76567F4C52300DAFA623D2A79D6D0BDA72B4B926FEE83C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_purge_jobhistory',
0xF64E507B4F7ACC343B411D3704A4FD5C6D574387AC389603798B49938881F798CAFB84469EFD7103935A50EAE7AFC8AADD704BF97CD53A2B7579887EB9B17FF799E24F2DB011E5C6B120001660831DC27FF90B33E5D7BC91A96B64E6E1510B83A3703F211A21FFA00E1F901064408A70ADE267227660B6EDCED2B7D0B9EE8D8F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_readrequest',
0xC4405832538A8595A12EA039F2702A11F87CF12BBF846EE75D5AE1255B55138D0808CAE8318D5AD37366C5CE0F86CFF3E4F9CB736F08F36077BB7D289AF61793B7257B1F5E4C807AEDB63EEB3C288FFD8715DE3377DE78D1EB3BF0C3CA6C3E54A7B55E41F9E562D695AED8C7586773ABAFD44AE973A13B962BC0D555D32F72AB)
 
  insert into #SqlAgentSignatures
  values
  ('sp_reassign_dtspackagecategory',
0x2DA8CD53A833992411919977452D70454CF34A6475D9A7105E79164A48B86183075F9929A9C4E0145367DA5438A5A9CFE5C2501D49FE4006579C985623E6EE7886D618107A0D8D5B626AFF4C263B4460FA24501C067AA1488106BA85AC49B5B4DC94ED8863BC147556DD5A7DF51A898EC5116939EA852E79B557EF174832B955)
 
  insert into #SqlAgentSignatures
  values
  ('sp_reassign_dtspackageowner',
0x2C0CE5DEE0346B46FFB874D2E12AFFF421F12511FF34092DEEA1165A3F47C0B2BE2BB8E9D73840B9E40A7221FEB381604713FE6FCEB93043D53AF204E76236E953F088C97C01FC2E8C158B9363E3AD1AA056F1BA5AEB19DD054436F962D56BC2AC781425439CBAD1B047F0E0C731C6E25AC8271BD552ED25465DEFB4BBC0D199)
 
  insert into #SqlAgentSignatures
  values
  ('sp_remove_job_from_targets',
0x5654CC98EF3B87D440E9526D9CBD0FC921E8294DAD3BE1F6F5C45D537290F943C79DFE922D14596D848ED867307CCE0253101867D75B092ED4AFC5D06D3D88C698930756CCAE633E23A3CD5D3939367852FD339712AA5D9E978DF699EF587A2F02FCC9F414A68D8B69D35701DFB4A27C67D09F22E4A0E59527906C8CE4207F4D)
 
  insert into #SqlAgentSignatures
  values
  ('sp_remove_log_shipping_monitor_account',
0x2574C6BA881A0A063C08DED5A911D018591143DAFBC6F1732DA51C627DFF7FF9FFC27113F05D0D5F2C14E4EE2C17AE741A2F1263E144E99951E695174E129B225E6F8E860651F69581D94A8DA2DC6B2585901ABCDD80ECF97731FBB0DEA27A6994D653CDDD5483D081F96E3E9BCE9F1C5E7DFFD9FBA2E1EBB0AAB7063EB09CAE)
 
  insert into #SqlAgentSignatures
  values
  ('sp_resync_targetserver',
0xC8F6D39F6BC409A2C0F8D8A52BACB5AC229F72E79640AC1B0F1372BE872992E46E68327A44887954A410B4EF19B554C8EF55E1211DFBE4784CF6CDBD76AC37F7F1370258B0948C272220925091CE00AA2BDE1E4D46DE0E7F81149936259C1C6548C76BFB6921B2A59AEE8DF40FC901E64941306BF729A6AA0E842353D4A60F7C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_revoke_login_from_proxy',
0x1E6EDDE40D175AD44E9279D7253CCA791F9AE8F125AC732BC1610291E50EE067BF3DEDCC345B3F3F9BAAD932BCD7C357076FDC2CB57870FEADD65EA874327A2257603357BDB8094C009E4DC5F32419689264CB42BFCB92E4064FC37D528152410EA3339D14BC8C4DBB50C9E5A0680A8D812F4843934DDBF3E50DA17974377610)
 
  insert into #SqlAgentSignatures
  values
  ('sp_revoke_proxy_from_subsystem',
0x868CEB96828A9D302178B33EA520FCF655CDCD145ACAC74059B9A6AC395766A7C9991FA1236A0BF9695842334E1A6B4F22B9A5C895D9BD72388B36B3A820D87DCE6A8A88CF4B14B57D6DC9725CB324505FF248115A5928528796CC6756407330CC833F5B92917485172D004BAE80A92BEEE46C6305C38A35EE8182EAA052A2A9)
 
  insert into #SqlAgentSignatures
  values
  ('sp_RunMailQuery',
0x7C8A5C9A18D3BF1A6859E1E0A5EDBA447C1065D80B4288F13DFEEA2D0D45771381FDF25AEE708E57DA1AC3BB2E503C16020BA712E74FA66BBA8B2FED1BC2C27CC9DE44AC7BEF34D328C8C62AF42203B670F8CB619C920C7463BDAB60F6CE9EE08095732D5ED78C29C3B0CDAAE7DC4BCFBDF1E7D32CAF7BBCB11DAD27A57550AE)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sem_add_message',
0x1FA66C31ADBE22A8DB93BB0C5B0D018F85A9A49F5F9A5E1B085A5BAF1C451E991871E40E953195C7FC8D3F371264167471DE23805084FC85D837857547B282017A663EF9B5D021EBE245B67BCB283C85A04A2F028B8DFAE95D50EA8191C8AFF27B11604BB72BA1D4EB51E280B4DD7B950BCD9DA6AAE6094547F366C91324E079)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sem_drop_message',
0xBC1DD3D95F5E40E80FD0B69A21A01D40A0F40CB074B9E072226EE0FC6EEADD28924808B5AD63E0BE9FA33760E618D4509055D18E64E7568028EAE260D3CF792C84E01AF6ACF97A6B755ACC4AA9E850366713F8C24AAEA053E50BA8FFB19D7E5C02D7C9F105699D8EBE0DEE29D5AEB97CA92DFAC2E357BAC7A43E4C290E2DB384)
 
  insert into #SqlAgentSignatures
  values
  ('sp_send_dbmail',
0x123276504343FA9CCA1AA45B72FD31B3E2FEDBBA745B33E6965AE5B726B5DB4280CCE193CB4C7C1468E3F29E1BCC9A5D01A980075343FFEE683B2175308A77268826BBD222657E4D194B8FF96DB6AE05D91CB086E44A964870B3B9FFE79663D36A5163CB0EEBAB0926B953737C69528305F86271CCF63CAE6D1EF02AA5031731)
 
  insert into #SqlAgentSignatures
  values
  ('sp_SendMailMessage',
0xAC4D517F36614C9FDE9529A60B675FF60243D4923682E145C7185E9B6B0B9965D8E8B86DE8F20567EEC3106CEEAA4B977A4E99F6EE6DD96F1DEE0D724E2E2FA1A670D91407C21B7E7A0B3429EC298489CF4077AA9A86E03C8D850360A07CC8A5C0BDCEE14F771E9D74B5A61D3C8E488719F559954C975631EC0A1FB4A2885304)
 
  insert into #SqlAgentSignatures
  values
  ('sp_SendMailQueues',
0xA7E3F534F52E93BF41AA36D1D0865D65D9AFEE3055FEBDF0AC25E1B467CEFB0027812AF09680E1F941A0E088520ACFD16A1CC1044C3BF4E90A3C8E1BE43C1A9F3E5609DE3CA2A9966958D477A4C0AE460257EF93F6FD19F16F2323B7A5508CFD636CFD90CB243E717F18742F8BC72E76481F422CCC7C1FFF3A6DD064879D1EBA)
 
  insert into #SqlAgentSignatures
  values
  ('sp_set_local_time',
0xE2A206853A2875EE069E6588826953E458E3A5689ECE6A3665CAFFC8D51C0829051380B1AD3405E5A1EE653F3AB9C046E202409102A4DA3F94ED00076C62DBEDD6D8B54D5D9A6590285A9841C8B81BABCF86B04404484394D188FF8FF8C4B4CE24E2515F6465B6C8EAF75AEFC82458087471ECCEBFFBAE9A61D70869E1F309B9)
 
  insert into #SqlAgentSignatures
  values
  ('sp_set_sqlagent_properties',
0x38995930E7ED84F5D23D2D6191BCEE6405E0D3CECA4D4BDD45C7928BF34299BCC50FC0C8A59D91E29C74C17E59851C33124C7B2D75770483E7A844318936B1C0076467DF75145CE71734E34E17EAA0DC6BD9DBD6BE52EA4BE25852122DF1E7D3F228B90E41B48C284112FC6BF4BAE598DE9C2892FAF0508C4BC8594F97A0BD7A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_check_msx_version',
0x3EC7B3F380B046891FD3BA6F6AAB69E575F40752B17F37130D2CBEDADFCB4FFA171B795F6B96BC15138BF2F4F2906CF9C66A61D00FFAC5CC4409E7F3908B643D6484871EE769C37520C70D947AA78899C80E475C2911E304EEB05A4845DFE13FA1F1CB73A46D4D9F7722ED701E4EBB3388FBBCC3B230E85C9D7E7723984B232A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_get_perf_counters',
0x7103F18DBF5CAF4085F007121F0EB6A775B36E0B7409DB709A7EBF844688CB7C9D71BC265D99658BBE2A01319D225407962FDE7FB40CF4ECB2C6515F53B85492FD5411C7F65ABA330FFBC1B40F59ABD3EAA591E359E0E96C718FB95EE126E398C6EC4FCF34F128698F6702632DA37F5BD8FB4D9ECA164D1045A6EC2EF49FA834)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_get_startup_info',
0xCBEFC51135DEB8A515556C4D28EA70F39EA70C64005A7D1A89EB9ABA96CA72B3DF2DBC29C2981FE366F0BB07826FDB9A91C9731116D62F48E1DEBCB9DF67ADF270E2C8C938B4B4D7B2A349A70D42DDFE6F924437152CBF1860CCEC7C67E8BC7EB0F7D1AD54755D40B6A8B599B1C7A154D59188B96A6F7355FEE3D66B64E34770)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_has_server_access',
0x9F74969161302692534764CEEF0C23363EFCC46C98218AD0462CD7E72A84FFE95E421A2A0DEE40CA5F32170BD7EEF1C59D049184EBD9BE8467603797789E53D376E672E55D407EA98155DC0423B7F56DFB815542C8E2960A0DD6F0D6398686B71A9317300DD0509986F5759D375F038BC6CC93972C35E25AB290327A6EC93E12)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_is_member',
0xA0AAC58456E753CA0FA739D32497AB56A8304E333EAE8AEA65A349C1426698773273240454A8C915A38414717D332E35E9BE9D0BE813158AE13F2D4DAC663F87E9DB7C6E7C891367E22FFBF8DC0C95141466C5E8BD80CDD3853FC4F1F2E9F84FC868EACCAD85779DEA290CEF3E13618E398B66AD15FA3A768A33D6E7157F6B50)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_is_srvrolemember',
0x0B2032C7BFAEE18E84BD32CEB9424FC552494E27C7BB61A8217070C97DD3E0AAE465CF7DB00448AF14DB147896EC72515CBC308D42FFC9280416D717BB131E1C8CE8CF6ED2238DD75AEE5398CF93FAB06C9EDA490659DBB59278596681F2C331880F9BA55C57F28BC3D5FC301C882DDA4FDC51F6787B6E6DEEA796F45102A08A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_log_jobhistory',
0xE8EFB5CD7A659FD1553C6F27E9CD966DB976D861B327E61FB2E9090F02AEBBA81E6194F03951AEABE1E22C5B2F9311CFE8D3228F9B05722260FD942135E9E05799AB59FE3DC96EC3BF4C1BBBFAC88A46E35362C50BEDCBC1CE919D2EC752B2A2625263B206AF614368EACDDA95996807344AD509C7CD8FB903E3F8ED6C933029)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_notify',
0x95979B64FF2AD307755D85416480389087E90F449B5AC71DAE5DF8E8B0160FAA0BD748EF0030DFB50752C4AA9F082B5ED2FF9F2EA2DB1D6C0F58411F2FE46CCFFEEC6C2966059A32DCC92C24C7FF67C46F61FFDE5A78F2DBC571B1DB19D4E5BE4EA3F42CFBBE407A4FDD6A79A97BDF7792C3DFAE0E661D907424A9CBCC5DB44C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_probe_msx',
0x3808E3736F107F23CD158E5E25AFDB3C548D11E653C5914D3E944E40CF803286225CCE35B98CD29ABB59E90BD93C4DD733D7305850808E231A8F9095F8454D3DE86FA65E583C95BE66ECF1C1D1B2AEA0C9CB25ADC8227285570EB00B6AC4B3089D19799AC98705FB5EE16B611FF9D5B794FECA8016C85F1C321CB202324BCE62)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sqlagent_refresh_job',
0xF1BCC544AFA00CF8546F704E0A7BC45548888D6A496DB40127635B3BF62068BE3B8D23FFB0AFCD3EF5698F32D89F81AECEFAFF85CAEB1DFA69078D6E072DCFA6ADD96BBDDE0FC7BFF8784484E1F8B16980BF65E1D9781B55595476268D02DD170A12FB35A826044EEA512E5143ABC20512973AD7FD66E286EF56FDB72866E62C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_addfolder',
0x9E567DD28AAD5A2D379BF5466CF3185E5702D84E357640FBE3B3DA018D6C6B12303BB192EBDDC210914B328756556CD66B24FB82BD76CAE19AC5A7EC37774529A31143605AF4CD308966FEC2B471331F5B059CCAAF76196FDE00CB7537D9F1E56CB3906131AC7618948D91D17D06A950B84F2E34A33FA6391378A3F909A8CB70)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_addlogentry',
0x8F11C108637535BB0D76331857E29EF035AC2F621915DF70E90C6ED6C4DB195D1588E082285D1596222E1D89613675A6B1FA554EA75233217108AA02D23A67BFE49E58E584C3EB6E42CAD13E2053F4CBB8CFCC0458014DB04F44517C9F925F397EFD8C8460FCB74A01AEB8791FA3EFD1F248A0461D0E8F806EB4D232B1D3F0B2)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_deletefolder',
0x2A1AA3DF7064B451113D19EB42A2E4CEA5993084E352280E4B754DAAD9D7CE4AA9EA055F846342E9CB8EC14A35B3A8D49959B1E888C54237BA9A5B2979221BF08D180F304176E1A668B001C4DD7B12444F64A6884EFA2A2B1752A6D84ECF274F273D675532C5F37C9F13EB52A0EAF699B22C06144727C557A794220A7807A802)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_deletepackage',
0x343237C3BA6B7E6C918D9F2335A299DCE1FDC3F8AEF3E14EF72C42022A3E0DEE8B9C923E68372A250D26192450541DC5E5BBE555D42D6D5870BF0BA2FAA274298E93BC579DC2AE63A3C8F64C2F5CFEA9D71F30D3EFB6CC4BCC7914E332F6D22E9C1F58BC783149B1D7FF94E9DC8FF8171D81792EFF4FF6C6E8C3EEE9B8A8C796)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_getfolder',
0xDE730E543B0ACA4816294E80B6B3A4E39E0AFA8E68C12A6CBD248615710517489BD2F070A6F81A9E41086A03BAFD54F8C8B66F537D0DC7FB54368F4A2702C1BCF702BDD1B42F0058513514ED1CE1965EFE6BA17A8C21A755E38F5474100D942D4C428F28B6DF5D60057D91E6732A3A46291535B4AF46B2D2B2C30A2F5B91AD20)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_getpackage',
0xE2859CC8DF8FCD8AABE354469AB731435F43FB1F76843EF776C1F7601BD27268E8ED19D6CE94483F98BCC90D8B66E36C09E99DFB384A3FFA04B94B46ED0ABF68B8DA109B2437406759635FF0F41E0D788A6D0D759F9EAF77316125BD4E8F6E3D061EE7E0CCD81340402D7034A9EABB52A0E4ED3C1B09B1C34A49EB7A45D81D62)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_getpackageroles',
0xB572595E536A0458F163739FD01A765371D9D1BC928DDE894844D8766DFA3A9F3F19A2D8E8BAE18305531001ED2122B635238458E7E56000174DE381E683F3E6AA4CECE01168728AC41C123F3B09965054C00F8FE1268139690BB51FFA0C56BA8BC39B5309E5F03A6FC41CCD3E0B68B0EBA29EAAF920CEE9F46AF89195CA9E73)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_listfolders',
0x06B73CC9F3F924107BA9737EABC8DE131CD641E594A32BE34F21FA5B89E04374999CD0DE1C90A22C9486F0FEEA9CF636377CD1E185C9C9216B6F4A0CB8EC78A8B06F0E3ACF8FAB7259A7E8FDF16F6E3A655E8A1A7E13870DD1AF8197B72CFAAFE7002B09048ABE84A11D67D5FE8A4C2F920737BBE0BDA8BF479FDF171AE72C4B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_listpackages',
0xD6B073C1F646AB91B1BD220D800F5865E3B1E28AB5D0F046A2A2E762CEE1D33089C47F7849BEA23F0AC7053967A00C8744D870DF8407DCEB4696E304D3CEBA36C3808AB548FA704B95CD7EC882CE9FD63B37B1B78637BADEFD55A289CE8B8D08FFCB968F77DAAB1FBE488EE7305BE40B589EE65BE4B9A7B760CFFAEA0F939592)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_putpackage',
0x6CA80E20A71BCA8909A454323104DE59782D60ECACCC18C5A939A30699E9005ACC81801735B848CC756F8914C02161D78476037F63FEDAB898839AF1F06D6717C072CE2C5D21623D13FBC60ADA0879843C7C99A4653AD65977D2634B66ED3B119769A3D95C45DAFC97B25FD2F40560D143218CEBCD98662F5CE0084259A8D562)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_renamefolder',
0x0B4E3FCE378BC76AB5A5F1652F757157BD204A20CF908CF68BAF6B09334D6C2DE18FE8BE7F3F58370BF871B73936B02C662A041C64249835A1615E68EC7110FF9FD052C2C010A38BA8BFD90B675B65BE2BE141CC2987399D69078A11214CB24C8247F4CC4F26BA1D725118921A67F2912B5BFAA6D45E9EEBE623FA40A0DED425)
 
  insert into #SqlAgentSignatures
  values
  ('sp_ssis_setpackageroles',
0xF3E9BE9E3485EFA89B5C47F426DF5E629B06CE679D09C9E49C91381A1A9A8B23EB78FE84E2003DA2069058561741D16D1291AC2210D9DBF613247EB194B2FEF813AD3256C39566CFAF33281E088C37346C4397A25437D0D97E8FB73587D7B178533951AB3A08CE4C19DA2F69FACC4E23D942CC53423C37F54B874B94968C123A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_start_job',
0xB867C75F7CC9A74B00B8FB06CDC17116EB4920AE238448698EC08D1A94D7B2159C2600479B80EB4C8ED134342A046044E51527A4B3C525B920D2093790C49CFB651B48A9E8E050A365E91F95B8A957D8C8044C0E6299BB0863489A01B0339D98F37086BE7D720725EE55EC25B1F26581FC1FCD60E5175E3FB1DB957320C44002)
 
  insert into #SqlAgentSignatures
  values
  ('sp_stop_job',
0xA505F210023664E8E8F60B9EF32B8D68A016593F13F8E5D3EE36F16CE08DB4D6EF2829CA2AB9BE8081BA1FE930A89D5E21B46130887CAAF5C9BC2CF9EE6BEED128B57E8015C2AA1750DB3EEFBBDDB8BF5C6A6E449805A37DBEFAC5FD4891AB5AD858825361D3060D97678FD05E63BCB163745B1ABC82BD686927CD03B1988500)
 
  insert into #SqlAgentSignatures
  values
  ('sp_sysmail_activate',
0x1C8D8A4EECDDB5AAB0B7A86DDDF2BF809DBEEA2649148C904791D597DC3CE37E3B2C58D5F7C7B91846FF56E009B929DC2B2C618D5A2288BF68F2CED90DF33136A3E9A07127ADD873D6A6CB9121AF2AAC1AAB97628ADCB79A3D1CE03F897CAEBEC1B583DDC0A76D408966A5F3F34734656724D6F1EFF97486E1449F5AC729A031)
 
  insert into #SqlAgentSignatures
  values
  ('sp_target_server_summary',
0x484932FF2DEB40DAA0AC71931BE7D7DDEFA0598FA7F5A06B1F6275DB43A777B3B93472A17BA19E768988B63F71E8138A8C0E1B118E86C4303213174A6719CF7EDA1EC2C2F7335FF7071425B6B73D3E3F5A1C6D6B7DDED1A966909B9A7986D1731784B387C8CAA4F8B8EA1B7324C17A2E00BC1B507993A5A5A6AB5314CCA18213)
 
  insert into #SqlAgentSignatures
  values
  ('sp_uniquetaskname',
0x5C5505AA309A8BCCD7E1747273DEACB0DE8E5AA8986633C564F5393C127D2B7CD2A0CA22D0B5A25ADB60BDF3B2C8DEB026A6A6DA8D7024838A2F18CF789B2E0A25B49700F77DC11B5B8E59EF4F3573631F7ED4AFC4D4532E6540727561D332928F6CF24891566246175901F0EFFB4D4DE11A7298A0F83D367CD090B17EE2AA09)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_alert',
0x608B818D62472FD2C666F0BD1291404860ECE6A0C9D11B6EECEE7E9FC0FC37A6F747501B9280B879F7AE3D97A0F4DEA744C253A99FBBDE460BD58B325A9BB67F5C70F06561FE22FAC08A6C984F3CCCA9F4C183E9863DABEECCC0A43ECC94C209144EF8068F8422FF4EFD97D399AB307C5A6BD182E57530AC598E8F7939F2A79A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_category',
0xC914D6D514A2E3C53324A2AC5C8CE186518AEEC6B87DCC17FFB58886F18B8DE58F7BE26243F5E8AE7F4F3E1615DDE2F721D858651E333B975AB7AB949F75EB1BE3F35F3961A4D1C6B68D1532E1EDCF9728C569FA54A2ABC894AA1E4B68C4D44F957637C153911FFCCDC069819167310F466AB7DB319BD877AE3489CDA788109A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_job',
0x02FB19A8BE29DC686E4D9AE02F9585DE1D49BDDB7FCB25653FA768D53B6958F6FAB780533C2A305A2D3B09DAC8D19B0BB19B46F0037A8D5D4348A8165CD46FA8CB869E58BC8762F068E3000B779F7A349129E375656B66FEE9377359FAC3B025B160DC86CEFE09173869FFF382AC39CB5F39898C14424D0E01C6399927EF3D36)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_jobschedule',
0xE52549D3BEE9A95528CA34B995A0A6E2177ECAB166BFA4EB4A9E01F3F9478C77FBE59B5A6402ABB197A00DCB1D06A8961078FD9A4316303F194C8B9086352568629157F4BE9A0F51632E27FEEBBA2A8DAE90FBED2C986092C9132BAAE5F1B7087F711489064EDEAAD69B634CC4D146CAB3A97D570DF16B1BAEE95BF2E997FCA2)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_jobstep',
0x84EAC8EFE9AEE2BD32E13ED4F5F3BEBA3099821D3BDF843A7E01922382FED0ED5D42CA5C5A8F7D9549DFF5E419E4C49904A9892BA68EE7E0399628A8DF3EAA59A046DEBD2C9CF2B49681C8AC4B2808F734CE10873A7E1B28736C71498FF484812A35D061C782EE771AA9CE4D948AB3EAF727C8840D8AB3B2A6BBAA582B4FCC49)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_log_shipping_monitor_info',
0xA013C300D77E6093683D108287D35DA63FD22467D2A6659E8042637223579C4502607341401820F16F669BE51C46E7CC29FBF876AF36CDBF4216834030892177100AACCE434AF593AEA793EE81B44E4BB0C1F8E7F9937ADE74137DB86B8FA56DA6FEAC90CA85D7EE0508ECDC911248AAFE326C3F2645A81082F4AA0545CCAB2A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_notification',
0x41AF513879A9CDF4A04782CD1300F5889B0868860BDC9AA1FBC60C2EB96D93F87A22E5D90937EC79A70499C3330F5928ED72186959078AC9692F72E6173671C0ED4AFBD83349FBA942E7A4B61D8D4D9746B6356FC2C0763CA3925BCD636428E3D18E5203F56693099E261EB961B19A4E45FCF845CA10E1087C32FB9463A30C85)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_operator',
0x61A2BE43D48FCBC6FA4D4C25EAB1A5A62AE83772FFAE30A6D20A18CBF00FCB49526DAF5019A09A923BEF816949AB9958060FA5482440D335862AE590423972BA6E93049C535BEE2AA3142CD88D22B4DE0DD04411482D308E4C600BB176C07F8946BE38C9CDDC1EE0C6ECAEB87603067BC2F78E68BF903000DFA2519DBDADB633)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_proxy',
0x805AB5ABCF434EE2D5C10431ABC2EDA64BE720AB20DEB413645435385EC6A34A611AA8AA5C9C33873DFC57BC37B207DA71D2822BD77F28852044A6CE7CDD99808F0613724882EE4EA3AC61361B7C532124DE14B02A1B25FD7CBFFE010EBCC0E15BD1AF3B27531DD33CB2762FF3B660538088D953014BE9E8049903FFD4DE97C3)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_replication_job_parameter',
0x7BA811306F8EE577B7D946516242993D0848E864B970D734268F5C6A5A4DDBEB3B8666ABCE1CF0F551841E8A72D88C94E48CAF8E62B2163A68AF1B9A34A2896143C3DA0D61E8365186728EB57F07786B805C5AA7F06679F9E3ADD0270B379EE7E3056ED630667562A80D0C4E1253DD68695E50D702E69B3ECB417A9EA29DDC8E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_schedule',
0x90B590210EE908F8F4E38A1B69EBE488679D7DDFBFC3B559F56ED5D022F44D0605649DDAC56C7927338CB3DAAC7BB4D5D870341B292D70084E6133E4028011E1C2481B3CC6C332E425462BBB7AB092FBAC89F1FF9A1A7B0F60729249C6796855D02F5E0FA571DB88F86CBDBE4CE774212811C43F89A02E4D001DEAD418237037)
 
  insert into #SqlAgentSignatures
  values
  ('sp_update_targetservergroup',
0x6089F6C9107B1087AA8BAC3B7531A51EA4C359EAD29A0288E0EDF886373EDD4399F05206C534AA914F270CB70BE1C28B70A29C706DA86769C47472C7DA56AF01149563D3B05FEF8E6B6F59B21508B9CEB7131D91575E215F8E55956E0D6295860AEA759CAF2DE1CB48829D4A6C0FFD628452CB980D5E1A55610C2595ECAAFE2B)
 
  insert into #SqlAgentSignatures
  values
  ('sp_validate_user',
0x9C88DA695504BB2E83861C4E31249097F469B674452C31F6D57402582A4EF7E9912702C2C18D051BDAC0635D4000DD65337661608D279E1209BA31E995CD99E80D16C286D0E5C8EC5356F7DDB1A5D0CACD150BA38ECB3C27DECA350EBEE549A3CA35D128007DC60251A85600898D8E6FE8591771241E5866994DD48AB2714392)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_alert',
0x5D7703C05B11FCC719E95DD4D53BCD5AF4D9F025EAD31A1A28C2F586B005C150A37217BE4FFB1FBA2C290197B9185F00C0C7205209C3A7D1757ADD03CF180945A886CB69C3434BF496106879BA27F98824BF2660EF1D38E07998256C9931B68FB5BBE08DD967CBFADC41CA95CA8F0411EAB5D4C90AA2493852948ED3977E73C2)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_category',
0xDD0A2154561985280A7BD7A6E7CA1DD16BED2BF9C247682FC4BAEAA5CEA1C1E891A94CE1C804BD79A0CEE9571D6F5F5DE1564974CC48150FE1EA4ED966F10385DD0D092C0606CE824D7BADC31A0887A00856FE8177D22BD00B1E5BE6734AA989D5AA7DCE02AEBFD99AFC1EF0511AB272810999EA1EFF6202D48ECC98173346A8)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_category_identifiers',
0x403A3D88BFA421DB46D1F3AA72F6DB0888D9C4C7C2B1A791897E5CDA2EE742029BEA89CBBA0D6369C270B9F59339EF68C49C79E501FE912964D077D6FF6738003C28D4DE588DEE876A275B2B22C9C7D4E5B2A4911B5A436C631DC53C203AD1B2294A89DDB8DF34D753600B43E0DC44AF9BC56BD997EDE8991F4F3C35470119BC)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_credential_identifiers',
0x25D0C2B93C17B43E64E17A2D4FDE450A3F030497889B92C2F632BC15E8427D9062350A4BC6E74C31C2AEE1A07F5C33CEAEC675B81210CBD20E6CE1248E855BE4BB80A81B7C0B8B32B83C217FAA18C0536EDDEFD3E4E0FEC4610B8EE16EF0A3C4E088E341059CFB8E5ED490AFF2C808B4E1BB7FCD017B352F45F8B276BE914D80)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_job',
0x20548D7637308F51B890F7CD5C444869B3928F8FEDBE109F577F7CDAE28D85833E54603B5DAF5F39CF6CCC5C365EE2F17D1ECC70C4545A89396357D92400DA70ED888E68612034A916591AD77BB8B3679EA3D48D23AE4CB0042A76DF89224604C7B433F1BB2F7E5B1901C3E097AD4B51F224865838D57F3CAA6BE22B1B59E317)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_job_date',
0xB2C16DDD4BB0B33F8992279CF3963A97D5645A11C084C208F067EF2467B1B052E1813874F54FE22C50793874B12737705660A302920985D2A47027F7BE96813B217BECC4104B94495D4F891BC0B98DCD6DDF3B4E57ABFC71F9CF8F1F906748CDC2E553B687AA34C0287B2F9761F94D7CBEA3BC524633260310666F7C6CD4E206)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_job_identifiers',
0xCFC1CC5694A9FFF83A7D847FCDC206F87D02E86B255E77A431A176391C2F1DE0700A3E6F14D633BB26BA3CA6FA2EEFB7F59ACA56E760D46BCFC45334DF1EE518B37A04FEC699BE7CB6AFE184B2F9D1931FA4A75E628C3B3BD4B5782710E616674EF68B22E7AF54BA85933956B99FF7449C374D33A5A772B5957F01BCDA8A1D07)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_job_time',
0x9EE7D7C0A6133A1033D7D9E0EE39078B3C85A2FC8D5CEBFB07A1AFA3C4B67C95E219092D9EC1EA7EEFC138AD83115081F1344A878D99027E13D2CFD78A48F97F1C3C24035A3F973923862CEBC16914F108A14610C33B01930C43713C4787E36E59B444FEBE868807B79DC2534D6E8B499593E8E7E0246EAAE5A67A486A88E084)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_jobproc_caller',
0xCFCED5D7103050799C3DF3AE1A9E16A0F77E8EC3982C62058D225163769925D36869C64BF8251E24EF7A121E246B8450DA43CF24C1A91E36895F7931CDD21F8B6F112DEA64A1DEAFEA8E81B3519D9F5AD2B0B250451AD44AE602A854F131FBE2C6A7389AA83FD6ED020C307F2F0F8CFC071D77DA095AA15FD44643275D80EB43)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_jobstep',
0xB12A6C75EB4FDF96150FE2D3E62D585F11B36C3C4019724524DA8046A63BC593499F3D378270E4D81E6CD045DD8C7FEEDF4FAF0B102D5ED35F97A3AC7A04BEB2AEAD13607E44C0C22046BE529D654095D40F40A4F9D65BE8B4D9E506A2A368EEFD0FE7136C7C049EEE5262CC665752ACFBE3BC38686ADC3CD5C2290AF855CA35)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_login_identifiers',
0x70641FE0648711783D9A24828926C06AE8EF7D09A8F9D6551A04B72BCF17B07BACD49BCDB6D56AA7FD746C40D210887CB97C1023ADC107524FB7230892199AA2A85AE06F62CB39AAE2D82832545903A1A1E862CBB992C4B0D67496B7335915E88B5E9CF2C58FA87DCB7954815B24D2A0F2989E863082BC2A198A1D8CAC81FC3F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_notification',
0x9A5F3B31BFC43B4FD130AE9E71F9512E281A3AADC342DD8FD3C2C32C24E02B8A5FD6052D27699D4438E270B8E1AB4B6F3A1488A21B0D9669CAD1ECFF14F68BAFA63176AE5A8092059FB31DEFE34FC107E84F704E6794EAADC8534A395ADF2870568BDC3941E2180EE8E568FBE1D37EF12F4A3148E35AC86289480DDA66B9B38C)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_operator',
0xE3C929BC644B49AE32A2EB5E7619EFFDC4EBDD3E4AC2CD608DA9837E80BB80766EEC3380B821CD12F36E31F2F6228A5887DA49F7B9464333B6A8306A2DFB2826338B41C6F2554157104A48E51E109CF6D4D4E6DB9541AF4AC8B0CC9BEA28F716D139FB6907E84FC319D3C15FABF2B6C5C96679D8665879222136BF4617D53C36)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_operator_identifiers',
0x78854626E4227741B4BE9F380EF50946195B3E7CAC6DC4399726C6450CBAFC75E3BB7C8AF0C35C22F4A3690DAAE953A63114D7640D7912EC5E78AB6321C7A0C805BFE38A55F19A31B7BFABAA52EE659EE6A2EF98A78071E5AD7B3EEC8240DFF0CE1CF8405A71C8ACD899DA4326985A426EB18370AB375DB5186711EFF7D41407)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_performance_condition',
0xD316207B724B099F51332DB8AD23E03AE24199DF99CA2AD22F761E6148B1CD95ACD076B74ADC4844B059E06738A7DCBEC86B1001B004F0E97E1DCCC46E2EF31C509FA225FAE730EBA448A499419F20D9BC0126EA74F07BAC79C0EC7362C685DBE666226B52E00A305AB974A27BDEC014BECF3585830BB3F3790CDCD414E45A93)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_proxy',
0x02F0648FE8DE4A507F83642737D44A904B7B6669BA364C069A2863A3162F0992E7400B9E753AB189D683C96464196C9A5E5D7D2C7C535987A76D8B99D3E1674CE160A1838202B4EE96CCCB68F22365DADB80FD9104F61718E87669149E0ED6C74E26E7918BBD2CB3AEBAA7BCF19C966E40B75267208C1190DB5D446FEDA5475F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_proxy_identifiers',
0xCAC28587AC3B7FD8B3501FBB29A770A8F50733A88A3AAB259A275E9E4FFF3B9BA0A4588521E533238EC9D5D99248CC90C12677BD01ACEB93D43862C6701BB7C007A46BFB4783090D2AFD8D68F74BC6C2951297A53306993E3695C108084227D4D633B2FC9A66632B15E0FE9E3CC4DF3E97B0EEC66023AA6EBAE80BBCC52FBF5F)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_proxy_permissions',
0x7493CA79E0BDE2B3B95FD47ABE10728D556A3E905C6C29A045F1A38CCF875794146CF807EF440F13E28A15CF0F5D89EDEBE93593FA8A6A4D81BE92FB42D054DF01C3B36704EFF1F7870A117A97623E06352719848B0EA3BA13A00E5ED20F410932C9C6DE398D594DB82F8B99F8BCB19EB882AE23D0EFDB947C92E8C457113E8E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_schedule',
0xEE88576C3364862AC8A4F0E089BA6FA240BCAA71307C0F15586CB84829FF166CE6E8F293EAB4DEF7FB014B4A5A93568306A3944699992FA3464F02065EAE9C5203B0BA7963CC6B8175131C3425C2F297BF7F146444FD460A64174DC8D1F6F83116D54B83BE9029D1BB9635DEC3E0EF9F2A0CD18B44D41797C250ADA1E05E4456)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_schedule_identifiers',
0x7478BF5F7A0A43FBFD783137923AAA63FADB79B5BF146933083C8DF04FC6EE6C61945CA8F2CE17B4829DE5E7DB15395C2346BB2D6461B4993B2F7DF2F5BC28AB0029E308E1CADA1F014D7F2A97A5227D1C260D78B22B4F260D0719380CB491D6641A44D55C4D94782D3D57E881290665C7144212E1520EA3F8FA3FB04B23927E)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_subsystem',
0x9225B22C78BD61BE895688B14797A40E4C7D9D3D7807498D60C491891CFFF3A18C5DE2093D5C9A23F359AA5D0F0B9A1E611084598657E23F9499B747F3F139EA812D47E227F5762FA1EE2ACEF9CBA1EB29030EA0383521A2695EFFE903B2934D27918D995A40F314961EB7407BF7C23647B1EBF2005F9C297AC616DF8B538225)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_subsystem_identifiers',
0x9F5A434FC19C73E73EE60A9528561F7B6CD3F955EA8F96FF78AAE75EA41634EA2DC9233471FBBC7069FB77BEF4A9F2261C39857B5DA98E41F05A1C0F2A7ED3709D6DA30442876B47EA5FFE1571390B8693BF5EFCBE16D6C98DDE7799D9C8F23B3673DF7A0044458A06EBBC748B3C0B4EC04EB74C91DE9EF43D33806D632305C2)
 
  insert into #SqlAgentSignatures
  values
  ('sp_verify_subsystems',
0x3CA4E1406959EE21A0ECE1D0E814421E490BB129B6B15AB4602AB8BFF1C364DD80C55D4CB241FEB510EBF48D7F46E956D22611486C7D68F1619E4A23FEB13C71B48086789EAA60E8FEEE4CD365A08D0224D7A3223C15D8D3CD582E4549DDDA4A32A81301441219F21875FC9B2A7048CA974267CBF0035A923ED534F4CFE4858A)
 
  insert into #SqlAgentSignatures
  values
  ('sp_write_sysjobstep_log',
0x900C06AF41EFD26A6E0A481BAA39654FB9E2BC7C72DEF0AE17C01D84C593BB89FF997F3CCF2FD6FFC12865D0C0241A5764E460CC5558EB2CF52BB150B88057A2D7714D951D6176315B16CC1BD2DFD9F927DF7483F44722D14D3890659F6EBA545BF6D798BC418E529B6F9FD08E909F9E3DD9B5D9290F100C3F3E0E6CEAECC8C4)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_add_account_sp',
0xF711D1280B328D05FAF498E05884F4A82061B69E29423314879CD27FC71E427261EFC89F91562DF7824FA74DBC857D8CA11815D1B231F2864C3D32C1AB368C68D1E268AF70A6544549386B2DA9EBB14FC0A1B8F4BB68DFB04B694FDF906DBC26427CA0D290BA32255486F59478109DCD93D1A73D9CB6E80E4046773EB39F7201)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_add_principalprofile_sp',
0xBD9F2F9A44375E2B8E0C644D3BCE32D546737CA1F09A0C12872C68E7AF855DECFA2E513E5D1FACA56C3D9906A71C82AE0E13963BC82D117A001AE72083A9903A49A63A9EB71E77147A3551382AD6225E201C4AB87DBAF1915E7D91D73E9EE8AC1076F5AC82FE0426F7953FC0EA7FBBB9042E169BFF0E62CB7324F2F16AB7614B)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_add_profile_sp',
0xDA02620811D2CCD517D1969E160ADEB8F3250187F14DAC317EDB10050C9218899141F34C680EC65B7681DDC2D4637799BC9D4E311CDF3123E1A19FF708980201060A55F90C889BDFBC0918EE998AEE971B68095887C621821CD8802A3F4D7A2EC82291148B6E995043379050DABEE094800DB05C31CA5D57B13574FB6ECBA713)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_add_profileaccount_sp',
0x908D5A81BF8437FED6C727D32BEDEAB38AABC68A04792A3A975B1C144D31348EBB897047C8280A2BDAF19284686BF260053B309F977FDFF25A770B3309F84644CD6F86D801E18274CADD1B42EE99273C95639596DAB5BF8002782AFD10B8CBFA5B3317A9FEBFADCBB639B8511FDBCCF3288B6CD88BE7A8EF72037E2A5085A78C)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_alter_user_credential_sp',
0x0D076C4564635FDAB510A96CF2F7FB7960BC9320E4311B002E0A4457C172AF5A55B1BE5D962F1B0B01769D967750FA6E1723B5919E48C62A13735E7D8D07C653163E0A1EED7F94A5456BE33C9CA078B78D4F09DC36C1756C51212B4FD623401074298148CE4E0BB226CA313ED721751E45677B855FF8BC5C79659EE74FD50E8F)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_configure_sp',
0xB11D00DA3742AB1A6F0A69BBB9C8304CEFA03E84B404742F2A421CFA7AA496D28961D293BBBC8B1F37E5D383379324B36DB547603822E51AC5DE55F13F820195BE1D9E82BC0FE549C0F8AEF7DF547FAB1A638B713F36EA06A8145EC0F1E3AF1AC8299A05DFE708289676FF6D6D42B429EB3F51B34DBFE4925186460B87EADD34)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_create_user_credential_sp',
0xD57F51F325C0A1EBC2BF1D3E1338EDA8C4273E22A593D6080E2B4ED9E8126032031B0B014C3B7E211BDCEF803A493940F710AD235EB40398BAF64AD267A6C15988AA6182F71128DF2565F3E3557BD36628F6F3B5DFBF47D1D0A45BAAF0913459B46585727937CF16307E5EA19BA426CDCE285D0CC84B80CB12043820F7AC568B)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_account_sp',
0x97F22A5CFD8FA7FB641D56739620835A7464069FB6EB0368D1F192C46591EF9482E1B95BB20E67633E28F86DBD73C7DC53E66A39EC199FA036F6086EF9BA952875EA28096FC30B60A1C78B1B5B31AD4BA28EE59A40C745F00B8CE506095737338D720FE188740E2CB78EFDF68AB65FAEE9DD7250F4920EED2265C3E28C3CD3B1)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_log_sp',
0x68D75FF5A3ACF72D4C36F89487C92F3EAC20FB7FE0049B140052A90934E576CA99AEBFFCA865615A23B3A4181711E3E0A10C7EE8D5388DC0D1147DDDBB1A95513B1743EC4B1B61BCF43A0625F57F567FC4333F1CA65E0D0BCC7D68D2ADA4217D554556FBF761C4C082911908876F3452EE391F52E87802EF8CA975707A58E1A0)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_mailitems_sp',
0x57BA6511B00855D030AB40958214255A09FDC9E379DE805F5DAC4F38CE0BA553FB64C9344FDF3558DB6715233158EC906FF0099A78B5FAFCF3370302E32990BAF847A30FCC2CB9F36AB789E122E8F2A94D1FD63877C7AC386D0E986952C29409344AE57738256B0A09D7E37FECBB10F4B5D70F10B63BE3F93B1EDF4BD22589A3)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_principalprofile_sp',
0xF31D9BB94E53D8DA002B5CA0357F105740047FA539AFE0995E58CE2B8ADD1893327E34BE4AB3E51E00AC560E093379F6933475DF1F0E97F9824E1F140F01A9AAA3A76CF932553FFA6D35CE885D7C58D471366AE1D0196F2F4F45DF8699EF596ABC5745D874BED1017D2E580723FFFF493FBD7E1C4371757EF1B11E0ABCE4750E)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_profile_sp',
0xCAE8212D1A484FCD1B846394DC43266E3E7B8335B5DC9111181E10ECC60F31B77A82734073C644AE7C1687C02F634173B17961455263B3AD3FE12F6B363E3A1EE15821BE521D87A71C7AE0ABD7C95284F08949B69DA9139E776DA1B534FD6AC09E8CEAF1012418620991972DB49A9807A59DD71D089E448B193328B862BEB2AA)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_delete_profileaccount_sp',
0x69483A3EA601EE6516879935723B7EA4BB56225F53DB9704DBADFC8344D8BF24EB691F3B52A940970F746C034AEAE32A384735212F3B45E2BA450D3FB65E1B4978DEB7FFA9E0B58CFAACCE9364EFAB5EA6C77310F7D7DA69570576C76D0C398825712E43F56F18B53653A64CE67D724CAECE7FA49B2D1CACF79B9C5EF554E843)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_drop_user_credential_sp',
0xC56D11EF37B6AD03F41EE2D64A2A5977CC8B8F931855267F82A610FC95542CC829D9AADAB0012B5ECEA3244FDB78CA42A55022B3C1568A4DB95523926CBB5A89EBCA02337CA2906B5DC9221DCD795A729FACB98743208E90C56418CB4B3E4AE0C5A48146B6BF8AF998100346DA6C5ECF37F4E8785CD3A1A5EF7BE303B5F05310)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_account_sp',
0xBA4DB6A027E480F7D769E44383F331A24D7A254FC092D5D3DA8FCCF3C3C298D3E36BFC76616BC6FF088A74A06B3D275E881AEB71F27C9FB83223CB52927B8EADC912CCB46FDD02AEB1D7B5354B335266A9F3F34B77C7A2BB62AFE3926E223791119486E0EFF47A7F4DFF31EF91AB451DF18E78DFFB51C4992AB74DED727D9B3E)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_admin_account_sp',
0xB4B7D4879BC3274EA652EF697422EC438A959AA2EBFABE4D3CA0B00EA6BAA83DDD52211404B6339152E06177C1DE3A0721480E6B7B04E24EF9EB1B85F34129DD2FFE4C6C67EDED183DBE994A5BCAF8C0C87927C44519735F0FACBD7B046246EA1D66D963E2A1ECACB28174E1B4CE33DBA1BE64F6AACCD69B57DC2ADF9A03CB20)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_configure_sp',
0xB831640803452B354066A838930C36EC6CCCA9868DD32B8FB700559D4E583600A37C9524942706828F6D7900B7917C2E52A8490690538F71ADC500DC0DDE8FD79DF20CB2DC8E3455EDE3E62DC73D50C717B2B243044927F0F9D6B5072FE73C036C6DB2822CE6686BB564539556A660B7A35936AAEB8B21DCA8300F11F33AFE4B)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_configure_value_sp',
0xDC5FB79D8FF80EAB22FCB2D97EC37CFE3D329D1DE692FC88B8378C77652FD87294ED6CE6EE3BBD9E14106A05FF9E9EFD5AD21DE04757E85024D6021B777400899E2EA7BC35D58C766F6F81EC1A823099CB0F20D519518F0765AD2795A97C81D2D889FCDCA4800C4655A97554E46923DF4E3DE229978E9E092D9A606D74FE8A21)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_principalprofile_sp',
0x87EF31146E9DB2E71DA372D8A4DE8E176490C7410B0C467AB159B675CCF38CC98A333F699787F552077904CF91879E4E1CC386E899CDCC0F583DB2FF186E4CE3A1FCEF0E291071CFB28293ED581F2D3DC4621A81E5E1F2770DAB90A2277C58EE2A9F769CD794BC2F575E4C545976152BDF68C904197E02F5627AE569E2368E13)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_profile_sp',
0x429CB6766711BD7E53089DD0E9EF282F2A339BE2A5FA05387D5A36D9DC73BAF8936F7467AF7FCF8211AE34C020A2069AA2BB3D0D5A2F69AAA72CF14044B248A0F8F2E85FFC0016D057E433E7D0E57CE178182901EF2A0AAAC17D10FC74ECE0CC33B6D0A84D3151FB313BAE42B94EC31F3B70B7801FB2B9DC3AE565D6BA36F6BA)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_profileaccount_sp',
0x80C794F879B464E740D256E6849CDC74BA15421B271EF75898AE89C628E08DACF4CD989FCF06180C7148B9E3B823E89A8A6AE20ED9768A60FCDA9CC0BB9C4CFC0A1306DE13E8A14622D0C54D120BE03C2524D55FC4F363DE37864244835DD1FF8A2519D027BEF6A7F54A8A6BB5E2D10ED0E9732F7A89A9E8CD70F79281163A17)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_queue_sp',
0x6F6B73AB2968B7A1DC5B186025656656FEC2FF947B75DDEC79644066757993E72EE11E7E401935B10EED1C5D808648C7F8F68E2C05916428B529832BECD4494203B3F74E6E64853AEC7E6EB9608F640E2625B45C59BB4A519F977C3AB25AB526C789659D1EB334159FD11B858A88CCFC8908F7C543838DC2E46EB5EC73F2C51C)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_help_status_sp',
0x1DB21E826A92E9A0095074892E874F8F16B6A5713EA868C185AC76D2F3820F41A651C2B6DB3AD9C6A67FFE36D9C7ECFBA7DADF69F6834D77289DA78F72596D223468380E3903891AFDF0195EF4E3A7FEF6BD61B9043C351E761037CA61B10BB7508A7EE5AD3A7B4D116F6C3871FD984314390D319ED9EE1B0512F6587972D81F)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_logmailevent_sp',
0x7264E13465D2AA64FC7DC15CCAF9125F2C31FA146948B9F7088A57385BE6DAE6D239F5ABD76A31F1A093B2451F4D1AFF613038F83607CD6912BB7552F9669C888E2046E25ECAF18311030267BB51EE8D79325F7821F047DACC6EBCA4733679CC9C8D186E4A94E253A2EBAA9567B36503EE99F89CB6FE8E3C1C9E8DBD8CD68D0A)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_start_sp',
0x352EF5F7D878A8B055D4C0B22E4008A9B0A4EAD6964B766321C3FFF8D426B23E8EE2313DD4CB92837DE3692AE94577425B3EF599830AC34B83EBE84EC612EE509BD23BF1C78EE05FC67F1D1FA1FEF7238FAD17D43DA932E38B4D2E5D0A33FEEF00AB7F967126B7F544DF809F590258ED5FDA82A6B8B8D80815D9AF56CD50BB4A)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_stop_sp',
0x17478DE2C47E14C6BA4BD57001D17B332D72043F2DF5039E0823F93B289977245147B4D1851E3130CFFC4C5D2FE8BAC58925229D5E4B8E2511D957C3B463F09B1CC304793D443338DAF35F03CD2BD7B66B36FCB138A8032BD28E8FCE28DCA18437DE4536C1351AE0A637A1E9B3B705D29C5BD4804B9AF134E5BBC1DC8E728C33)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_update_account_sp',
0xDB2165F74976F25E340ABB9ADA065895060E6A708422B59F799687B43EB85FB3177A066F475A71D3791797F3666A819910519636C21D9DA9C1507671724BEE457E614DA01AAD322369202FBFEC1B2078D0A75C10ED3D2061963451381E64E56BA23A409AE388A33E76BDA6EA47E2F00429BA560112B7B384D22B212A50E6FF81)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_update_principalprofile_sp',
0xF46A160A5EFF929C3041F0C8A35420E2B7C0016DD0528AB048E9EC2B1041E5A7E5BC4A7253826C421F00A144BC96DA3823884C048CF7FDB743C1B58E7CBF6492B9EE3024E39BD96FF135FD0E407AD97CC5BFE3A327906CB04C029CFB669D00B06473C32EE470C466AFF4C5DA086471CA4F504E4846BFA3D543C648B84202C568)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_update_profile_sp',
0x8FEECC91555009322F2D939F47F4F4835CB14C80B1ECE4389D35172688041F827ABCAA0302C8AB96625305A41E7B59E5E8451D7C9DCB6F700DA6A0CD77EBEE9AE2F90B4D0C99F57F8EA9E7771FF5553D547C33B25CF76C43DD59DBBBBC5408335FC30D326F5E1447C9EE0CBB93063B71681B15ACFF617DEAFB6E2A814D1D1B03)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_update_profileaccount_sp',
0xA6B52D4AD519876D17A88DF5CEE1266E25BC08FC5298367CE0025632CF92D1BAFFE126BE4AB86652BE987B3CAEE07194554E14A9E6F026A2B8FCCBD68CBA78122C5F5AB9E34AE3B2A8971973130045112CC64BE1F3C778DF8192CC459047B35C13C1F5F8A779397CBE54745F0C46FBD0E3C55D98981B072C11F5049D1EEAC920)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_verify_account_sp',
0x5B1497E598BA0FC6BAE8A147095517C24F1C760F304EA7AD255927D22DC41B00D00366DF8807B4728D70912E460080A98515B1118465A279138860490CA62F2D51A6820E1249AD9C7619EAD56CDD59DEDCF09751CDE968866C471BFE3AFA8D8451997F473F8818F8DD87FB0B9325BF6872C6FF5080F1FA6C895FB4B75F8B7513)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_verify_accountparams_sp',
0xC2052592F6491BB6D491CB6B6B324612F19B361B50A03104AD6A0E8ED23BDE2BA18F3568886704E5A25A9054804977DC62A7429ABBC7DE20AD2039B98442C4B6B975F8132798C940F76A125B5C6A3E9EB6682ED0925CB8905368E4D785E390DDA18FB337336A094933964396926A1365B5E39AD84CC982A3FB5F5DCC4C6F0D7A)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_verify_principal_sp',
0xBDC4C10AFF781C2C1B26A907BD4995AA7607F060660D57A38E965490A449C51A4B5C090539BCFA33E7C92757EC68391AD29F87C93440CB49C0EF41E474E848F628A1E00396B744C2A22D329B40E5D283060BD4934E2B20F0261B6DEB10D71F44795DB4C79418E74E0052EE6C131FA58FE3C70A601AB379BCC2FC2061D3466963)
 
  insert into #SqlAgentSignatures
  values
  ('sysmail_verify_profile_sp',
0x60B394BAA2A1B9A71B13EA8766C8753FC46FB9A5610876F5EEA27C28B05897D0FBE0760B5A87CD7262265A6C3EB47E0BA7F80C7C95D3722E4E6027C2A1521A9B9EA5746AA7BC8200F60ED7EFEC31A48ACEF3E18BF527C7132F33C1DA6AA22D7655AB6B93ECE569A21CFB971C60045092DF8B9144B2833446688DE78D6FB494B1)
 
  insert into #SqlAgentSignatures
  values
  ('trig_targetserver_insert',
0xFBF9277865EE4EA98603EBAC1782E211EB23036544454AA8EE633B89B7706D2321B809FF8C97B3E8852F41C9D574AAB8021FA211F6099CA3E4BC0E97FFC7DEBB659E676FF52C6508A4FE3FCF406EB1C3233D6822CA0C85CCE78DDA52E0DFD925678B7EDAD8CF959AF9C5B56A0F1310ABEA38F2E41C2435CD1CFAAD0D1C43033C)
 
END
GO
-- End of AgentSignaturesToTempTable.sql
/**********************************************************************/
/* MSDB8TO9.SQL                                                       */
/*                                                                    */
/* Upgrades 7.x, 8.x and 9.0 to 10.0 and drops all obsolete 8.x       */
/*                                                                    */
/*
** Copyright Microsoft, Inc. 1994 - 2008
** All Rights Reserved.
*/
/**********************************************************************/

PRINT '----------------------------------------'
PRINT 'Starting execution of PREINSTMSDB100.SQL'
PRINT '----------------------------------------'

use msdb
go
-- Check that we're in msdb
IF (DB_NAME() <> N'msdb')
  RAISERROR('A problem was encountered accessing msdb. upgrade script terminating.', 20, 127) WITH LOG
go

CHECKPOINT
go
--set compatibily level to 100
sp_dbcmptlevel @dbname = 'msdb',  @new_cmptlevel = '100'

go

-- Allow updates to system catalogs so that we can fully manipulate our system objects
EXECUTE master.dbo.sp_configure N'allow updates', 1
go
RECONFIGURE WITH OVERRIDE
go

/**************************************************************/
/* Record time of start of creates                            */
/**************************************************************/
SELECT start = getdate() INTO #InstMsdb
go

--preserve existing object permnission during upgrade
--create perms table
IF (NOT OBJECT_ID(N'dbo.upgrade_perms', 'U') IS NULL)
BEGIN
  DROP TABLE dbo.upgrade_perms
END
-- upgrade_perms is filled with current permission of objects in MSDB
-- the structure of table is:
-- state_desc = GRANT|DENY
-- permission_name = SELECT|EXECUTE|UPDATE ...
-- object_name = grantor name
-- grantee_name = grantee name

CREATE TABLE dbo.upgrade_perms(state_desc nvarchar(60), permission_name sysname, object_name sysname, grantee_name sysname)
CREATE INDEX indnc ON dbo.upgrade_perms(object_name)
DECLARE @state_desc			  nvarchar(60)
DECLARE @permission_name	sysname
DECLARE @object_name		  sysname
DECLARE @grantee_name		  sysname 

DECLARE perms_cursor CURSOR LOCAL FOR 
	SELECT state_desc, permission_name, OBJECT_NAME(major_id), USER_NAME(grantee_principal_id) from msdb.sys.database_permissions 
  WHERE state_desc IS NOT NULL AND 
  permission_name IS NOT NULL AND 
  OBJECT_NAME(major_id) IS NOT NULL AND 
  USER_NAME(grantee_principal_id) IS NOT NULL 	

OPEN perms_cursor
   FETCH NEXT FROM perms_cursor INTO @state_desc, @permission_name, @object_name, @grantee_name
   WHILE (@@fetch_status = 0)
   BEGIN
      INSERT dbo.upgrade_perms(state_desc, permission_name, object_name, grantee_name)
      VALUES(@state_desc, @permission_name, @object_name, @grantee_name) 
      FETCH NEXT FROM perms_cursor INTO @state_desc, @permission_name, @object_name, @grantee_name
   END
DEALLOCATE perms_cursor
go


------------------------VIEWS UPGRADE---------------------------------------


------------------------TABLE UPGRADE---------------------------------------
--create an populate sysoriginatingservers
use msdb
go

IF (NOT EXISTS (SELECT *   --just a safe belt, this table shouldn't be in 8.x
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sysoriginatingservers')
              AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysoriginatingservers...'
  CREATE TABLE dbo.sysoriginatingservers
  (
    -- There is only a single MSX server record in this table (originating_server_id = 1)
    -- 0 is generated by sysoriginatingservers_view and indicates the local server
    originating_server_id	INT 		CONSTRAINT CK_originating_server_id_MustBe_1 CHECK (originating_server_id = 1) 
									    DEFAULT (1) UNIQUE CLUSTERED,				
    originating_server    sysname		NOT NULL UNIQUE NONCLUSTERED,
    --Mark this record as a MSX server entry
    master_server         bit			CONSTRAINT CK_master_server_MustBe_1 CHECK (master_server = 1) 
									    DEFAULT (1)	
  )
END
go

IF (NOT EXISTS (SELECT t.name FROM msdb.sys.all_columns c JOIN msdb.sys.all_objects t 
                ON c.object_id = t.object_id 
                WHERE c.name = 'originating_server_id' and t.name = 'sysjobs' and t.type = 'U'))
BEGIN                
  PRINT ''
  PRINT 'Adding column originating_server_id to table sysjobs...'
  --add new column 9.0 originating_server_id
  ALTER TABLE sysjobs WITH NOCHECK 
  ADD originating_server_id INT NULL
END
go

DECLARE @MSXServerName        sysname
DECLARE @LocalServerName      sysname
DECLARE @UpdateOrgServerTSQL  nvarchar(MAX)

SELECT @LocalServerName = UPPER(CONVERT(sysname, SERVERPROPERTY('servername')))

EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
                                        N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
                                        N'MSXServerName',
                                        @MSXServerName OUTPUT,
                                        N'no_output'

SELECT @MSXServerName = LTRIM(RTRIM(UPPER(@MSXServerName)))
IF (@MSXServerName = '') SELECT @MSXServerName = NULL

IF (@MSXServerName IS NOT NULL)
BEGIN
  IF (NOT EXISTS( SELECT * FROM dbo.sysoriginatingservers 
                  WHERE originating_server_id = 1 AND originating_server = @MSXServerName
                  AND master_server = 1))
    BEGIN
      PRINT ''
      PRINT 'Populate table sysoriginatingservers...'
      INSERT INTO sysoriginatingservers( originating_server_id, originating_server,  master_server) 
      VALUES(1, @MSXServerName, 1)
    END  
END

IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sysjobs')
              AND (type = 'U')))
BEGIN
  IF (EXISTS (SELECT t.name FROM msdb.sys.all_columns c JOIN msdb.sys.all_objects t 
                  ON c.object_id = t.object_id 
                  WHERE c.name = 'originating_server' and t.name = 'sysjobs' and t.type = 'U'))
  BEGIN                

    PRINT ''
    PRINT 'Populate new column originating_server_id of table sysjobs...'
    --set this column based on the value of 8.0 only column originating_server 
	  --if MSX server is NULL we come up with server name that cannot exit, a generated GUID
    SELECT @UpdateOrgServerTSQL = 
    '
    UPDATE sysjobs SET originating_server_id = 
    CASE UPPER(originating_server) 
      WHEN ''' + @LocalServerName + ''' THEN 0 --local_server_id 
      WHEN ''' + ISNULL(@MSXServerName, CONVERT(sysname, NEWID()))   + ''' THEN 1 --msx_server_id 
      ELSE 0 --7.0 (local) or bad data 
    END
    '
    EXECUTE( @UpdateOrgServerTSQL)
    
    PRINT ''
    PRINT 'Drop column originating_server of table sysjobs...'
    --drop 8.0 column originating_server
    DROP INDEX sysjobs.nc2
    ALTER TABLE sysjobs DROP COLUMN originating_server
  END
END  
go

--normalize 8.0 sysjobschedules into 9.0 sysschedules and sysjobschedules
IF NOT EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sysschedules')
              AND (type = 'U'))
BEGIN
--create first sysschedules table  
	PRINT ''
	PRINT 'Creating table sysschedules...'

	CREATE TABLE dbo.sysschedules
	(
	schedule_id            INT IDENTITY     PRIMARY KEY CLUSTERED,
	schedule_uid           UNIQUEIDENTIFIER NOT NULL,
	originating_server_id  INT              NOT NULL, 
	name                   sysname          NOT NULL,
	owner_sid				       varbinary(85)	  NOT NULL, 
	enabled                INT              NOT NULL,
	freq_type              INT              NOT NULL,
	freq_interval          INT              NOT NULL,
	freq_subday_type       INT              NOT NULL,
	freq_subday_interval   INT              NOT NULL,
	freq_relative_interval INT              NOT NULL,
	freq_recurrence_factor INT              NOT NULL,
	active_start_date      INT              NOT NULL,
	active_end_date        INT              NOT NULL,
	active_start_time      INT              NOT NULL,
	active_end_time        INT              NOT NULL,
	date_created           DATETIME         NOT NULL  DEFAULT (GETDATE()),
	date_modified          DATETIME         NOT NULL  DEFAULT (GETDATE()),
	version_number         INT              NOT NULL  DEFAULT (1)
	)
-- CREATE UNIQUE CLUSTERED INDEX clust ON sysschedules(job_id, name)
-- CREATE UNIQUE NONCLUSTERED INDEX nc1 ON sysschedules(schedule_id)
END
go
--a system object cannot be renamed, turn off marking system object trace to alloe renaming of temp_sysjobschedules
dbcc traceoff(1717, -1) 

go
-- create temp cross 9.0 table temp_sysjobschedules
IF EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'temp_sysjobschedules')
              AND (type = 'U'))
BEGIN
  DROP TABLE dbo.temp_sysjobschedules
END
go

PRINT ''
PRINT 'Creating table temp_sysjobschedules'	
CREATE TABLE dbo.temp_sysjobschedules
	(
	schedule_id		         INT					    REFERENCES dbo.sysschedules(schedule_id),
	job_id                 UNIQUEIDENTIFIER REFERENCES dbo.sysjobs(job_id),
	next_run_date          INT              NOT NULL   DEFAULT 0,
	next_run_time          INT              NOT NULL   DEFAULT 0
	)
go

DECLARE @dynamicSQL nvarchar(4000)
IF (EXISTS (SELECT t.name FROM msdb.sys.all_columns c JOIN msdb.sys.all_objects t 
                ON c.object_id = t.object_id 
                WHERE c.name = 'name' and t.name = 'sysjobschedules' and t.type = 'U'))
BEGIN	
  PRINT ''
  PRINT 'Moving schedule data ...'	
	SET IDENTITY_INSERT dbo.sysschedules ON
  SELECT @dynamicSQL =
  '
	INSERT INTO dbo.sysschedules
	(
		schedule_id            ,
		schedule_uid           ,
		originating_server_id  ,
		name                   ,
		owner_sid				       ,
		enabled                ,
		freq_type              ,
		freq_interval          ,
		freq_subday_type       ,
		freq_subday_interval   ,
		freq_relative_interval ,
		freq_recurrence_factor ,
		active_start_date      ,
		active_end_date        ,
		active_start_time      ,
		active_end_time        ,
		date_created           
	)
	SELECT
		js.schedule_id            ,
		NEWID()                   ,
		0                         , --local server. TO DO make sure local server = 0
		js.name                   ,      
		j.owner_sid               ,      
		js.enabled                   ,
		js.freq_type              ,
		js.freq_interval          ,
		js.freq_subday_type       ,
		js.freq_subday_interval   ,
		js.freq_relative_interval ,
		js.freq_recurrence_factor ,
		js.active_start_date      ,
		js.active_end_date        ,
		js.active_start_time      ,
		js.active_end_time        ,
		js.date_created           
	FROM
  dbo.sysjobs j JOIN dbo.sysjobschedules js ON j.job_id = js.job_id
	  
	INSERT INTO dbo.temp_sysjobschedules
	(
		schedule_id		        ,
		job_id                ,
		next_run_date         ,
		next_run_time         
	)
	SELECT
		js.schedule_id          ,
		js.job_id               ,
		js.next_run_date        ,
		js.next_run_time          
	FROM dbo.sysjobs j JOIN dbo.sysjobschedules js ON j.job_id = js.job_id
'
  EXECUTE (@dynamicSQL)

	SET IDENTITY_INSERT dbo.sysschedules OFF

	IF (EXISTS (SELECT *
				FROM msdb.dbo.syscolumns
				WHERE (id = OBJECT_ID(N'sysjobschedules'))
				AND (name = N'date_created')
				AND (cdefault <> 0)))
	  EXECUTE sp_unbindefault N'sysjobschedules.date_created'

	DROP TABLE dbo.sysjobschedules
	EXECUTE sp_rename 'temp_sysjobschedules', 'sysjobschedules'
	EXECUTE (N'CREATE UNIQUE CLUSTERED INDEX clust ON dbo.sysjobschedules(job_id, schedule_id)')
	PRINT ''
	PRINT 'Updating schedules done'
END	
go

--just a safe belt
IF EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'temp_sysjobschedules')
              AND (type = 'U'))
BEGIN
  DROP TABLE dbo.temp_sysjobschedules
END
go

--alter only if command column is not already nvarchar(max)
IF (NOT EXISTS (SELECT c.* FROM msdb.sys.all_columns c JOIN msdb.sys.all_objects t 
                ON c.object_id = t.object_id 
                WHERE (c.name = 'proxy_id' OR c.name = 'step_uid') AND t.name = 'sysjobsteps' AND t.type = 'U'))
BEGIN
  PRINT ''
  PRINT 'Adding proxy_id, step_uid  columns to sysjobsteps table'  
  ALTER TABLE sysjobsteps ADD
        proxy_id INT NULL,
        step_uid UNIQUEIDENTIFIER NULL
END
go

--rename DTS subsystem to SSIS
IF (OBJECT_ID('dbo.sysjobsteps', 'U') IS NOT NULL)
BEGIN
    UPDATE dbo.sysjobsteps SET subsystem = N'SSIS' WHERE UPPER(subsystem collate SQL_Latin1_General_CP1_CS_AS) = N'DTS'
END
go

--to be safer populate sysjobsteps with guids, otherwise step table logs are not possible
EXECUTE (N'UPDATE sysjobsteps SET step_uid = NEWID() WHERE step_uid IS NULL')
go

--if there is no index for step_uid, create it, so step table logs can reference it
IF NOT EXISTS (SELECT name FROM sys.indexes WHERE name = N'nc2' and object_id = object_id(N'[dbo].[sysjobsteps]') )
BEGIN
  EXECUTE (N'CREATE UNIQUE NONCLUSTERED INDEX nc2 ON sysjobsteps(step_uid)')
END
go


--alter sysdownloadlist table
PRINT ''
PRINT 'Alter table sysdownloadlist...'
ALTER TABLE sysdownloadlist ALTER COLUMN source_server sysname
ALTER TABLE sysdownloadlist ALTER COLUMN target_server sysname
go

--alter sysjobhistory  table
PRINT ''
PRINT 'Alter table sysjobhistory...'
ALTER TABLE sysjobhistory ALTER COLUMN server sysname
go

IF EXISTS (SELECT * FROM msdb.dbo.sysobjects WHERE name = N'sysjobhistory' and type = 'U')
BEGIN
  UPDATE  msdb.dbo.sysjobhistory
  SET     server = CONVERT(sysname, SERVERPROPERTY('servername'))
  WHERE   UPPER(server) = '(LOCAL)'
END
go

--alter systargetservers table
PRINT ''
PRINT 'Alter table systargetservers...'
ALTER TABLE systargetservers  ALTER COLUMN server_name sysname
go

--drop syssubsystems table if it exists( to support update from IDW(n) to RTM)
--it will recreated later with the updated schema
IF (OBJECT_ID('dbo.syssubsystems', 'U') IS NOT NULL)
BEGIN
  DROP TABLE dbo.syssubsystems
END

--drop column logshipping from sysdbmaintplans table
--alter only if command column is not already nvarchar(max)
IF (EXISTS (SELECT c.* FROM msdb.sys.all_columns c JOIN msdb.sys.all_objects t 
                ON c.object_id = t.object_id 
                WHERE (c.name = 'logshipping') AND t.name = 'sysdbmaintplans' AND t.type = 'U'))
BEGIN
  ALTER TABLE sysdbmaintplans DROP COLUMN logshipping
END
go

--make sure 
--it will recreated later with the updated schema
IF (OBJECT_ID('dbo.sysjobstepslogs', 'U') IS NOT NULL)
BEGIN
  ALTER TABLE dbo.sysjobstepslogs  ALTER COLUMN log_size bigint
END

-- sysproxylogin upgrade
-- sysproxylogin upgrade
BEGIN TRY
	IF EXISTS (SELECT * FROM msdb.dbo.syscolumns WHERE name='principal_id' and id =
			(SELECT OBJECT_ID(N'dbo.sysproxylogin', 'U')))
	BEGIN
		-- convert data from principal_id to sid
		exec sp_executesql N'
		DECLARE @sid varbinary(85)
		DECLARE @principal_id int 

		DECLARE principal_sid_cursor CURSOR LOCAL 
		FOR
		SELECT distinct principal_id
		FROM dbo.sysproxylogin WHERE (sid IS NULL) AND (flags = 2)

		OPEN principal_sid_cursor 
		FETCH NEXT FROM principal_sid_cursor INTO @principal_id
		WHILE (@@fetch_status = 0)
		BEGIN
		    SELECT @sid=sid FROM msdb.sys.database_principals WHERE principal_id=@principal_id

			IF @sid IS NOT NULL -- principal_id is valid
			BEGIN
				UPDATE dbo.sysproxylogin
				SET sid = @sid
				WHERE principal_id = @principal_id
			END
			ELSE
			BEGIN
				DELETE FROM dbo.sysproxylogin
				WHERE principal_id = @principal_id
			END
			FETCH NEXT FROM principal_sid_cursor INTO @principal_id
		END
		CLOSE principal_sid_cursor 
		DEALLOCATE principal_sid_cursor
		'

		-- remove obsolete column
		DROP INDEX sysproxylogin.clust
		ALTER TABLE dbo.sysproxylogin DROP COLUMN principal_id
        CREATE UNIQUE CLUSTERED    INDEX clust ON sysproxylogin(proxy_id, sid, flags)
	END
END TRY
BEGIN CATCH
	print 'There was a problem upgrading sysproxylogin table.'
	print 'Unable to map existing principal_id values to sid column'
	print 'Error State: ' + convert(varchar(10),ERROR_STATE() )
END CATCH

GO

/**************************************************************/
/* Mark system objects                                        */
/**************************************************************/
declare  @start datetime
		,@name  sysname
select @start = start from #InstMsdb
declare newsysobjs cursor for select name from sys.objects where schema_id = 1 and create_date >= @start
open newsysobjs
fetch next from newsysobjs into @name
while @@fetch_status = 0
begin
	Exec sp_MS_marksystemobject @name
	fetch next from newsysobjs into @name
end
deallocate newsysobjs
drop table #InstMsdb
go

EXECUTE master.dbo.sp_configure N'allow updates', 0
go
RECONFIGURE WITH OVERRIDE
go


/**************************************************************/
/* DMF Pre-upgrade steps                                      */
/**************************************************************/

PRINT 'DMF pre-upgrade steps...'
--
-- >>> CTP5 -> CTP6 Upgrade
--
-- The check is based on presense of ObjectSet tables
--  We also check if principal DMF objects is there
--  if it's not we either upgrade from Yukon
--  or there is nothing to upgrade anyway
IF (OBJECT_ID('[dbo].[syspolicy_policies_internal]', 'U') IS NOT NULL)
	AND (OBJECT_ID('[dbo].[syspolicy_object_sets_internal]', 'U') IS NULL)
BEGIN
	BEGIN TRY
		-- Open transaction - we don't want to delete tables if we don't have a copy of data
		BEGIN TRANSACTION
		-- Create upgrade marker
		CREATE TABLE dbo.dmf_upgrade (id int)
	
		-- STORE DATA
		SELECT * INTO msdb.dbo.tmp_syspolicy_target_sets_internal FROM syspolicy_target_sets_internal 
		SELECT * INTO msdb.dbo.tmp_syspolicy_target_set_levels_internal FROM syspolicy_target_set_levels_internal 
		SELECT * INTO msdb.dbo.tmp_syspolicy_policies_internal FROM syspolicy_policies_internal 
		SELECT * INTO msdb.dbo.tmp_syspolicy_system_health_state_internal FROM syspolicy_system_health_state_internal 
		SELECT * INTO msdb.dbo.tmp_syspolicy_policy_execution_history_internal FROM syspolicy_policy_execution_history_internal 
		SELECT * INTO msdb.dbo.tmp_syspolicy_policy_execution_history_details_internal FROM syspolicy_policy_execution_history_details_internal 
	
		-- Delete policies to invoke the trigger that removes dependent objects (jobs, if any).
		DELETE [dbo].[syspolicy_policies_internal]
		-- T-SQL Policy jobs are now gone, we must nullify job_id to not violate the foreign key constraint
		UPDATE msdb.dbo.tmp_syspolicy_policies_internal SET job_id = NULL
		
		-- DROP TABLES (WITH DEPENDENCIES)	
		IF (OBJECT_ID('[dbo].[syspolicy_target_set_levels_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_target_set_levels_internal]
		IF (OBJECT_ID('[dbo].[syspolicy_target_sets_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_target_sets_internal]
		IF (OBJECT_ID('[dbo].[syspolicy_policy_execution_history_details_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_policy_execution_history_details_internal]
		IF (OBJECT_ID('[dbo].[syspolicy_policy_execution_history_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_policy_execution_history_internal]
		IF (OBJECT_ID('[dbo].[syspolicy_system_health_state_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_system_health_state_internal]
		IF (OBJECT_ID('[dbo].[syspolicy_policies]', 'V') IS NOT NULL) DROP VIEW [dbo].[syspolicy_policies]
		IF (OBJECT_ID('[dbo].[syspolicy_policies_internal]', 'U') IS NOT NULL) DROP TABLE [dbo].[syspolicy_policies_internal]
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
            IF (XACT_STATE() <> 0)
            BEGIN
                ROLLBACK TRANSACTION;
            END

            DECLARE @ErrorMessage   NVARCHAR(4000);
            DECLARE @ErrorSeverity  INT;
            DECLARE @ErrorState     INT;
            DECLARE @ErrorNumber    INT;
            DECLARE @ErrorLine      INT;
            DECLARE @ErrorProcedure NVARCHAR(200);
            SELECT @ErrorLine = ERROR_LINE(),
                   @ErrorSeverity = ERROR_SEVERITY(),
                   @ErrorState = ERROR_STATE(),
                   @ErrorNumber = ERROR_NUMBER(),
                   @ErrorMessage = ERROR_MESSAGE(),
                   @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');
            PRINT 'ERROR: DMF CTP5 to CTP6 upgrade tasks failed' 
            RAISERROR (14684, @ErrorSeverity, -1 , @ErrorNumber, @ErrorSeverity, @ErrorState, @ErrorProcedure, @ErrorLine, @ErrorMessage);
	END CATCH;
END
GO
--
-- <<< CTP5 - CTP6 Upgrade
--

/**************************************************************/
/* End of DMF Pre-upgrade steps                               */
/**************************************************************/


/**********************************************************************/
/* DC Pre-upgrade steps                                               */
/**********************************************************************/
GO
PRINT 'DC pre-upgrade steps...';

--
-- CTP6->CTP6 Refresh
--

-- Drop the parent_log_id->log_id self reference
IF ((OBJECT_ID ('dbo.syscollector_execution_log_internal') IS NOT NULL) 
	AND (OBJECT_ID('dbo.FK_syscollector_execution_log_parent_log_id', 'F') IS NOT NULL))
BEGIN
    PRINT 'Dropping [FK_syscollector_execution_log_parent_log_id]';
    ALTER TABLE [dbo].[syscollector_execution_log_internal] DROP CONSTRAINT [FK_syscollector_execution_log_parent_log_id];
END

--
-- >>> CTP5 -> CTP6 Upgrade
--
-- Change int log_id columns to bigint 
IF (OBJECT_ID ('dbo.syscollector_execution_log_internal') IS NOT NULL) AND EXISTS (
    SELECT * 
    FROM sys.columns AS c
    INNER JOIN sys.types AS t ON c.system_type_id = t.system_type_id
    WHERE [object_id] = OBJECT_ID ('dbo.syscollector_execution_log_internal')
        AND c.name = 'log_id' AND t.name = 'int'
    )
BEGIN
    BEGIN TRY
        PRINT 'Starting log_id int -> bigint conversion'
        BEGIN TRANSACTION PreInstMsdb100_DCUpgrade
        -- Drop PK/FK constaints referencing log_id columns so we can change the data types of these columns
        PRINT 'Dropping [FK_syscollector_execution_stats_log_id]';
        ALTER TABLE [dbo].[syscollector_execution_stats_internal] DROP CONSTRAINT [FK_syscollector_execution_stats_log_id];
        PRINT 'Dropping [PK_syscollector_execution_stats]';
        ALTER TABLE [dbo].[syscollector_execution_stats_internal] DROP CONSTRAINT [PK_syscollector_execution_stats]; 
        PRINT 'Dropping [PK_syscollector_execution_log]';
        ALTER TABLE [dbo].[syscollector_execution_log_internal] DROP CONSTRAINT [PK_syscollector_execution_log];
        
        -- Truncate the DC log table to avoid causing unnecessary delays during CTP upgrade
        PRINT 'Truncating [syscollector_execution_log_internal]...';
        TRUNCATE TABLE [dbo].[syscollector_execution_log_internal];
        -- log_id values stored in syscollector_execution_stats will no longer be valid after we have truncated the log table
        PRINT 'Truncating [syscollector_execution_stats_internal]...';
        TRUNCATE TABLE [dbo].[syscollector_execution_stats_internal];
        
        -- Change the data type of all log_id columns
        PRINT 'Changing log_id column datatypes...';
        PRINT '   syscollector_execution_stats_internal.log_id';
        ALTER TABLE [dbo].[syscollector_execution_stats_internal] ALTER COLUMN [log_id] bigint NOT NULL;
        PRINT '   syscollector_execution_log_internal.log_id';
        ALTER TABLE [dbo].[syscollector_execution_log_internal] ALTER COLUMN [log_id] bigint NOT NULL; 
        PRINT '   syscollector_execution_log_internal.parent_log_id';
        ALTER TABLE [dbo].[syscollector_execution_log_internal] ALTER COLUMN [parent_log_id] bigint NULL;
    END TRY
    BEGIN CATCH
        IF (XACT_STATE() <> 0)
        BEGIN
            ROLLBACK TRANSACTION;
        END

        DECLARE @ErrorMessage   NVARCHAR(4000);
        DECLARE @ErrorSeverity  INT;
        DECLARE @ErrorState     INT;
        DECLARE @ErrorNumber    INT;
        DECLARE @ErrorLine      INT;
        DECLARE @ErrorProcedure NVARCHAR(200);
        SELECT @ErrorLine = ERROR_LINE(),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState = ERROR_STATE(),
               @ErrorNumber = ERROR_NUMBER(),
               @ErrorMessage = ERROR_MESSAGE(),
               @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');
        PRINT 'ERROR: DC CTP5 to CTP6 upgrade tasks failed' 
        RAISERROR (14684, @ErrorSeverity, -1 , @ErrorNumber, @ErrorSeverity, @ErrorState, @ErrorProcedure, @ErrorLine, @ErrorMessage);
    END CATCH;
END
GO

-- Re-create the PK/FK constraints that we dropped in order to modify column datatypes
IF (OBJECT_ID ('dbo.syscollector_execution_log_internal') IS NOT NULL) AND NOT EXISTS (SELECT * FROM sys.objects WHERE name = 'PK_syscollector_execution_log' AND [schema_id] = SCHEMA_ID ('dbo'))
BEGIN
    BEGIN TRY
        PRINT 'Creating PK_syscollector_execution_log...';
        ALTER TABLE [dbo].[syscollector_execution_log_internal] ADD CONSTRAINT [PK_syscollector_execution_log] 
        PRIMARY KEY CLUSTERED (log_id ASC);
    END TRY
    BEGIN CATCH
        -- If we're still in the transaction started by the prior batch, roll it back so that it's 
        -- as if we never dropped any constraints
        PRINT 'ERROR: DC CTP5 to CTP6 upgrade tasks failed to create [PK_syscollector_execution_log] ' 
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
    END CATCH;
END
GO
IF (OBJECT_ID ('dbo.syscollector_execution_stats_internal') IS NOT NULL) AND NOT EXISTS (SELECT * FROM sys.objects WHERE name = 'PK_syscollector_execution_stats' AND [schema_id] = SCHEMA_ID ('dbo'))
BEGIN
    BEGIN TRY
        PRINT 'Creating PK_syscollector_execution_stats...';
        ALTER TABLE [dbo].[syscollector_execution_stats_internal] ADD CONSTRAINT [PK_syscollector_execution_stats] 
        PRIMARY KEY CLUSTERED (log_id ASC, task_name ASC, log_time DESC);
    END TRY
    BEGIN CATCH
        PRINT 'ERROR: DC CTP5 to CTP6 upgrade tasks failed to create [PK_syscollector_execution_stats] ' 
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
    END CATCH;
END
GO
IF (OBJECT_ID ('dbo.syscollector_execution_stats_internal') IS NOT NULL) AND NOT EXISTS (SELECT * FROM sys.objects WHERE name = 'FK_syscollector_execution_stats_log_id' AND [schema_id] = SCHEMA_ID ('dbo'))
BEGIN
    BEGIN TRY
        PRINT 'Creating FK_syscollector_execution_stats_log_id...';
        ALTER TABLE [dbo].[syscollector_execution_stats_internal] ADD CONSTRAINT [FK_syscollector_execution_stats_log_id] 
        FOREIGN KEY (log_id) REFERENCES [dbo].[syscollector_execution_log_internal] (log_id)
            ON DELETE CASCADE;
    END TRY
    BEGIN CATCH
        PRINT 'ERROR: DC CTP5 to CTP6 upgrade tasks failed to create [FK_syscollector_execution_stats_log_id] ' 
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
    END CATCH;
END
GO

IF (@@TRANCOUNT > 0) COMMIT TRANSACTION;
GO
IF (OBJECT_ID ('dbo.syscollector_execution_log_internal') IS NOT NULL)
BEGIN
    EXEC sp_refreshview 'dbo.syscollector_execution_log'
    EXEC sp_refreshview 'dbo.syscollector_execution_stats'
END
GO
--
-- <<< CTP5 - CTP6 Upgrade
--

--
-- >>> Delete auto-generated T-SQL packages stored in msdb. 
--

IF OBJECT_ID ('dbo.syscollector_tsql_query_collector') IS NOT NULL
BEGIN
    RAISERROR ('Deleting cached auto-generated T-SQL Data Collection packages from msdb...', 0, 1) WITH NOWAIT

    /*
    ** We have a row in [syscollector_tsql_query_collector] for each T-SQL collection item, and 
    ** each item has a collection and an upload package. There's a DELETE trigger on this table 
    ** that will take care of deleting the packages from sysssispackages for us.  The packages 
    ** will be re-generated automatically the next time their parent collection set's collection 
    ** package runs. 
    */ 
    DELETE FROM syscollector_tsql_query_collector
END
--
-- <<< Delete auto-generated T-SQL packages stored in msdb. 
--
GO

PRINT 'End of DC pre-upgrade steps.';

/**********************************************************************/
/* End of DC Pre-upgrade steps                                        */
/**********************************************************************/
GO


PRINT ''
PRINT '----------------------------------------'
PRINT 'Execution of PREINSTMSDB100.SQL complete'
PRINT '----------------------------------------'
go

/**********************************************************************/
/* INSTMSDB.SQL                                                       */
/*                                                                    */
/* Installs the tables, triggers and stored procedures necessary for  */
/* supporting local (and multi-server) jobs, alerts, operators, and   */
/* backup history.  These objects are used by SQL SMO, SQL Management */
/* Studio, SQLServerAgent, DMF and Data Collector                     */
/*                                                                    */
/* Also contains SSIS (Data Transformation Services) tables and       */
/* stored procedures for local SQL Server storage of SSIS Packages.   */
/*                                                                    */
/*                                                                    */
/* Copyright Microsoft, Inc. 1994 - 2008                              */
/* All Rights Reserved.                                               */
/*                                                                    */
/**********************************************************************/

PRINT '----------------------------------'
PRINT 'Starting execution of INSTMSDB.SQL'
PRINT '----------------------------------'
go


--this version of instmsdb should be executed only against 10.0 servers
IF (@@microsoftversion / 0x01000000) <> 10
BEGIN
      RAISERROR('This version of instmsdb.sql should only be executed against 10.0 servers.', 20, 127) WITH LOG 
END
go

-- disable the event collection for policies while running this script
IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = N'syspolicy_server_trigger')
    DISABLE TRIGGER [syspolicy_server_trigger] ON ALL SERVER 
GO

IF EXISTS (SELECT * FROM sys.service_queues where name = N'syspolicy_event_queue')
    ALTER QUEUE [syspolicy_event_queue] WITH ACTIVATION (STATUS = OFF)
GO

/*********************************************************************/
/* Create auxilary procedure to enable OBD (Off By Default component */
/*********************************************************************/
CREATE PROCEDURE #sp_enable_component     
   @comp_name     sysname, 
   @advopt_old_value    INT OUT, 
   @comp_old_value   INT OUT 
AS
   BEGIN
   SELECT @advopt_old_value=cast(value_in_use as int) from sys.configurations where name = 'show advanced options';
   SELECT @comp_old_value=cast(value_in_use as int) from sys.configurations where name = @comp_name; 
   EXEC sp_configure 'show advanced options',1;
   RECONFIGURE WITH OVERRIDE;
   EXEC sp_configure @comp_name, 1; 
   RECONFIGURE WITH OVERRIDE;
   END
go

CREATE PROCEDURE #sp_restore_component_state 
   @comp_name     sysname, 
   @advopt_old_value    INT, 
   @comp_old_value   INT 
AS
   BEGIN
   EXEC sp_configure @comp_name, @comp_old_value; 
   RECONFIGURE WITH OVERRIDE;
   EXEC sp_configure 'show advanced options',@advopt_old_value;
   RECONFIGURE WITH OVERRIDE;
   END
go

-- Explicitly set the options that the server stores with the object in sysobjects.status
-- so that it doesn't matter if the script is run using a DBLib or ODBC based client.
SET QUOTED_IDENTIFIER OFF -- We don't use quoted identifiers
SET ANSI_NULLS ON         -- We don't want (NULL = NULL) == TRUE
go
SET ANSI_PADDING ON       -- Set so that trailing zeros aren't trimmed off sysjobs.owner_login_sid
go

-- Allow updates to system catalogs so that all our SP's inherit full DML capability on
-- system objects and so that we can exercise full DDL control on our system objects
EXECUTE master.dbo.sp_configure N'allow updates', 1
go
RECONFIGURE WITH OVERRIDE
go

/**************************************************************/
/*                                                            */
/*      D  A  T  A  B  A  S  E    C  R  E  A  T  I  O  N      */
/*                                                            */
/**************************************************************/

IF (NOT EXISTS (SELECT name
                FROM master.dbo.sysdatabases
                WHERE (name = N'msdb')))
BEGIN
  PRINT 'Creating the msdb database...'
END
go

USE master
go

SET NOCOUNT ON

-- NOTE: It is important that this script can be re-run WITHOUT causing loss of data, hence
--       we only create the database if it missing (if the database already exists we test
--       that it has enough free space and if not we expand both the device and the database).
DECLARE @model_db_size    INT
DECLARE @msdb_db_size     INT
DECLARE @sz_msdb_db_size  VARCHAR(10)
DECLARE @device_directory NVARCHAR(520)
DECLARE @page_size        INT
DECLARE @size             INT
DECLARE @free_db_space    FLOAT

SELECT @page_size = 8

IF (NOT EXISTS (SELECT name
                FROM master.dbo.sysdatabases
                WHERE (name = N'msdb')))
BEGIN
  -- Make sure that we create [the data portion of] MSDB to be at least as large as
  -- the MODEL database
  SELECT @model_db_size = (SUM(size) * @page_size)
  FROM model.dbo.sysfiles

  IF (@model_db_size > 3072) -- 3 is the minimum required size for MSDB (in megabytes)
    SELECT @msdb_db_size = @model_db_size
  ELSE
    SELECT @msdb_db_size = 3072

  SELECT @device_directory = SUBSTRING(filename, 1, CHARINDEX(N'master.mdf', LOWER(filename)) - 1)
  FROM master.dbo.sysaltfiles
  WHERE (name = N'master')

  -- Drop any existing MSDBData / MSDBLog file(s)
  DECLARE   @advopt_old_value    INT 
  DECLARE   @comp_old_value   INT
  EXECUTE #sp_enable_component 'xp_cmdshell', @advopt_old_value out, @comp_old_value out
  EXECUTE(N'EXECUTE master.dbo.xp_cmdshell N''DEL ' + @device_directory + N'MSDBData.mdf'', no_output')
  EXECUTE(N'EXECUTE master.dbo.xp_cmdshell N''DEL ' + @device_directory + N'MSDBLog.ldf'', no_output')
  EXECUTE #sp_restore_component_state 'xp_cmdshell', @advopt_old_value, @comp_old_value

  -- Create the database
  PRINT ''
  PRINT 'Creating MSDB database...'
  SELECT @sz_msdb_db_size = RTRIM(LTRIM(CONVERT(VARCHAR, @msdb_db_size)))
  EXECUTE (N'CREATE DATABASE msdb ON (NAME = N''MSDBData'', FILENAME = N''' + @device_directory + N'MSDBData.mdf'', SIZE = ' + @sz_msdb_db_size + N'KB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
                         LOG ON (NAME = N''MSDBLog'',  FILENAME = N''' + @device_directory + N'MSDBLog.ldf'',  SIZE = 512KB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%)')
  EXECUTE (N'ALTER DATABASE msdb SET DB_CHAINING ON')
  PRINT ''
END
ELSE
BEGIN
  PRINT 'Checking the size of MSDB...'

  DBCC UPDATEUSAGE(N'msdb') WITH NO_INFOMSGS

  -- Make sure that MSDBLog has unlimited growth
  ALTER DATABASE msdb MODIFY FILE (NAME = N'MSDBLog', MAXSIZE = 2TB)

  -- Determine amount of free space in msdb. We need at least 2MB free.
  SELECT @free_db_space = ((((SELECT SUM(size)
                              FROM msdb.dbo.sysfiles
                              WHERE status & 0x8040 = 0) -
                             (SELECT SUM(reserved)
                              FROM msdb.dbo.sysindexes
                              WHERE indid IN (0, 1, 255))) * @page_size) / 1024.0)

  IF (@free_db_space < 2)
  BEGIN
    DECLARE @logical_file_name sysname
    DECLARE @os_file_name      NVARCHAR(255)
    DECLARE @size_as_char      VARCHAR(10)
   
    SELECT @logical_file_name = name,
           @os_file_name = filename,
           @size_as_char = CONVERT(VARCHAR(10), size*8 + 2048) -- size column in sysaltfiles is in number of 8KB pages
    FROM master.dbo.sysaltfiles
    WHERE (name = N'MSDBData')
    set @os_file_name = QUOTENAME(@os_file_name,'''')
    PRINT 'Attempting to expand the msdb database...'
    EXECUTE(N'ALTER DATABASE msdb MODIFY FILE (NAME = N''' + @logical_file_name + N''',
                                               FILENAME = N' + @os_file_name + N',
                                               SIZE =' + @size_as_char + N'KB)')    
    IF (@@error <> 0)
      RAISERROR('Unable to expand the msdb database. INSTMSDB.SQL terminating.', 20, 127) WITH LOG
  END
  PRINT ''
END

EXECUTE (N'ALTER DATABASE msdb SET TRUSTWORTHY ON')

go

-- truncate log on checkpoint
ALTER DATABASE msdb 
SET RECOVERY SIMPLE
go

USE msdb
go

-- Check that we're in msdb
IF (DB_NAME() <> N'msdb')
  RAISERROR('A problem was encountered accessing msdb. INSTMSDB.SQL terminating.', 20, 127) WITH LOG
go

-- Add the guest user
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysusers
                WHERE (name = N'guest')
                  AND (hasdbaccess = 1)))
BEGIN
  PRINT ''
  EXECUTE sys.sp_adduser N'guest'
END
go

CHECKPOINT
go

/**************************************************************/
/* Record time of start of creates                            */
/**************************************************************/
SELECT start = getdate() INTO #InstMsdb
go

/**************************************************************/
/*                                                            */
/*              T  A  B  L  E     D  R  O  P  S               */
/*                                                            */
/**************************************************************/

SET NOCOUNT ON

DECLARE @build_number   INT
SELECT @build_number = @@microsoftversion & 0xffff

-- Do any necessary changes based on build number here



/**************************************************************/
/* drop certificate signature from Agent signed sps           */
/**************************************************************/

BEGIN TRANSACTION
declare @sp sysname
declare @exec_str nvarchar(1024)
declare ms_crs_sps cursor global for select object_name(crypts.major_id) 
   from sys.crypt_properties crypts, sys.certificates certs
   where crypts.thumbprint = certs.thumbprint
   and crypts.class = 1
   and certs.name = '##MS_AgentSigningCertificate##'
open ms_crs_sps
fetch next from ms_crs_sps into @sp
while @@fetch_status = 0
begin
   if exists(select * from sys.objects where name = @sp)
   begin
      print 'Dropping signature from: ' + @sp
      set @exec_str = N'drop signature from ' + quotename(@sp) + N' by certificate [##MS_AgentSigningCertificate##]'
      Execute(@exec_str)
      if (@@error <> 0)
      begin
         declare @err_str nvarchar(1024)
         set @err_str = 'Cannot drop signature from ' + quotename(@sp) + '. Terminating.'
         close ms_crs_sps
         deallocate ms_crs_sps
         ROLLBACK TRANSACTION
         RAISERROR(@err_str, 20, 127) WITH LOG
         return
      end
   end
   fetch next from ms_crs_sps into @sp
end
close ms_crs_sps
deallocate ms_crs_sps
COMMIT TRANSACTION
go


---------------------------------------------------------------
-- Replication Datatype mapping tables
---------------------------------------------------------------

-- REVIEW - Is this needed? What does this do?
exec sys.sp_MSrepl_dropdatatypemappings
go

CHECKPOINT
go

/**************************************************************/
/*                                                            */
/*                     D  E  F  A  U  L  T  S                 */
/*                                                            */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'default_sdl_error_message')
                  AND (type = 'D')))
  EXECUTE('CREATE DEFAULT default_sdl_error_message AS NULL')
go
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'default_current_date')
                  AND (type = 'D')))
  EXECUTE('CREATE DEFAULT default_current_date AS GETDATE()')
go
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'default_zero')
                  AND (type = 'D')))
  EXECUTE('CREATE DEFAULT default_zero AS 0')
go
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'default_one')
                  AND (type = 'D')))
  EXECUTE('CREATE DEFAULT default_one AS 1')
go

/**************************************************************/
/*                                                            */
/*                       T  A  B  L  E  S                     */
/*                                                            */
/**************************************************************/

/**************************************************************/
/* SYSPROXIES                                              */
/**************************************************************/
IF (OBJECT_ID(N'dbo.sysproxies', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table sysproxies...'
   CREATE TABLE dbo.sysproxies
   (
      proxy_id             INT               IDENTITY,   --used to identify a proxy
      name                  sysname       NOT NULL,   --friendly name of a proxy
    credential_id         INT           NOT NULL,
      enabled                TINYINT       NOT NULL,  
      description           NVARCHAR(512) NULL,     --nvarchar(512)  
    user_sid              VARBINARY(85) NOT NULL,  --sid of proxy NT user
    credential_date_created  DATETIME   NOT NULL   --the date the associated credential has been created   
   )
   CREATE UNIQUE CLUSTERED    INDEX clust ON sysproxies(proxy_id)
   CREATE UNIQUE NONCLUSTERED INDEX nc1   ON sysproxies(name) 
END
go

IF (OBJECT_ID(N'dbo.syssubsystems', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table syssubsystems...'
   CREATE TABLE dbo.syssubsystems
   (
      subsystem_id       INT         NOT NULL,                       -- used to identify the subsystem 
      subsystem          NVARCHAR(40)  COLLATE database_default NOT NULL,    -- Name of subsystem
      description_id     INT         NULL,                           -- Message number of description string. These messages are stored in sysmessages table for localization purposes. Same story as for Shiloh
      subsystem_dll      NVARCHAR(255) COLLATE database_default NULL,        -- Store full path of the name of subsystem dll  subsystem are always installed in the binn folder of an instance
      agent_exe          NVARCHAR(255) COLLATE database_default NULL,        -- Full path to the executable that use the subsystem
      start_entry_point  NVARCHAR(30)  COLLATE database_default NULL,        -- Function called when initializing subsystem
      event_entry_point  NVARCHAR(30)  COLLATE database_default NULL,        -- Function called when executing a subsystem step 
      stop_entry_point   NVARCHAR(30)  COLLATE database_default NULL,        -- Function called when unloading a subsystem 
      max_worker_threads INT           NULL                                  -- Number of maximum concurrent steps for a subsystem 
   )
   CREATE UNIQUE CLUSTERED    INDEX clust ON syssubsystems(subsystem_id)
   CREATE UNIQUE NONCLUSTERED INDEX nc1   ON syssubsystems(subsystem) 
END
go

IF (OBJECT_ID(N'dbo.sysproxysubsystem', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table sysproxysubsystem...'

   CREATE TABLE dbo.sysproxysubsystem
   (
      subsystem_id INT           NOT NULL,  --  used to identify the subsystem 
      proxy_id     INT           NOT NULL,  --  used to identify the proxy 
   )
   CREATE UNIQUE CLUSTERED    INDEX clust ON sysproxysubsystem(subsystem_id, proxy_id)
END
go

IF (OBJECT_ID(N'dbo.sysproxylogin', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table sysproxylogin...'

   CREATE TABLE dbo.sysproxylogin
   (
      proxy_id     INT           NOT NULL,  --used to identify the proxy 
    sid          VARBINARY(85) NULL,       --keep logins, fixed server roles or msdb database roles
      flags        INT           DEFAULT 0 NOT NULL   -- tells is member_id is login = 0, server fixed role, msdb role. 
   )
   CREATE UNIQUE CLUSTERED    INDEX clust ON sysproxylogin(proxy_id, sid, flags)
END
go

PRINT ''
PRINT 'Creating view sysproxyloginsubsystem_view...'
go
IF (NOT OBJECT_ID(N'dbo.sysproxyloginsubsystem_view', 'V') IS NULL)
  DROP VIEW sysproxyloginsubsystem_view
go
CREATE VIEW sysproxyloginsubsystem_view
AS
SELECT ps.subsystem_id AS subsystem_id, pl.proxy_id AS proxy_id, pl.sid AS sid, pl.flags AS flags
FROM sysproxylogin pl JOIN sysproxysubsystem ps ON pl.proxy_id = ps.proxy_id
go

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sqlagent_info')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sqlagent_info...'

  CREATE TABLE sqlagent_info
  (
  attribute sysname       NOT NULL,
  value     NVARCHAR(512) NOT NULL
  )
END
go

/**************************************************************/
/* SYSDOWNLOADLIST                                            */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysdownloadlist')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysdownloadlist...'

  CREATE TABLE sysdownloadlist
  (
  instance_id         INT IDENTITY     NOT NULL,
  source_server       sysname          NOT NULL,
  operation_code      TINYINT          NOT NULL,
  object_type         TINYINT          NOT NULL,
  object_id           UNIQUEIDENTIFIER NOT NULL,
  target_server       sysname        NOT NULL,
  error_message       NVARCHAR(1024)   NULL,
  date_posted         DATETIME         NOT NULL,
  date_downloaded     DATETIME         NULL,
  status              TINYINT          NOT NULL,
  deleted_object_name sysname          NULL
  )

  EXECUTE sys.sp_bindefault default_sdl_error_message, N'sysdownloadlist.error_message'
  EXECUTE sys.sp_bindefault default_current_date,      N'sysdownloadlist.date_posted'
  EXECUTE sys.sp_bindefault default_zero,              N'sysdownloadlist.status'

  CREATE UNIQUE CLUSTERED INDEX clust ON sysdownloadlist(instance_id)
  CREATE NONCLUSTERED     INDEX nc1   ON sysdownloadlist(target_server)
  CREATE NONCLUSTERED     INDEX nc2   ON sysdownloadlist(object_id)
END
go

/**************************************************************/
/* SYSJOBHISTORY                                              */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobhistory')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobhistory...'

  CREATE TABLE sysjobhistory
  (
  instance_id          INT IDENTITY     NOT NULL,
  job_id               UNIQUEIDENTIFIER NOT NULL,
  step_id              INT              NOT NULL,
  step_name            sysname          NOT NULL,
  sql_message_id       INT              NOT NULL,
  sql_severity         INT              NOT NULL,
  message              NVARCHAR(4000)   NULL,
  run_status           INT              NOT NULL,
  run_date             INT              NOT NULL,
  run_time             INT              NOT NULL,
  run_duration         INT              NOT NULL,
  operator_id_emailed  INT              NOT NULL,
  operator_id_netsent  INT              NOT NULL,
  operator_id_paged    INT              NOT NULL,
  retries_attempted    INT              NOT NULL,
  server               sysname          NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON sysjobhistory(instance_id)
  CREATE NONCLUSTERED     INDEX nc1   ON sysjobhistory(job_id)
END
ELSE
BEGIN
  ALTER TABLE sysjobhistory ALTER COLUMN
    message NVARCHAR(4000)   NULL
END
go


/**************************************************************/
/* sysoriginatingservers                                      */
/**************************************************************/
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysoriginatingservers')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysoriginatingservers...'

CREATE TABLE dbo.sysoriginatingservers
(
  -- There is only a single MSX server record in this table (originating_server_id = 1)
  -- 0 is generated by sysoriginatingservers_view and indicates the local server
  originating_server_id INT      CONSTRAINT CK_originating_server_id_MustBe_1 CHECK (originating_server_id = 1) 
                             DEFAULT (1) UNIQUE CLUSTERED,           
  originating_server    sysname     NOT NULL UNIQUE NONCLUSTERED,
  --Mark this record as a MSX server entry
  master_server         bit         CONSTRAINT CK_master_server_MustBe_1 CHECK (master_server = 1) 
                             DEFAULT (1)  
)

END
go


/**************************************************************/
/* trig_sysoriginatingservers_delete                          */
/**************************************************************/
PRINT ''
PRINT 'Creating trigger trig_sysoriginatingservers_delete...'

IF NOT OBJECT_ID('dbo.trig_sysoriginatingservers_delete', 'TR') IS NULL
    DROP TRIGGER dbo.trig_sysoriginatingservers_delete
GO
CREATE TRIGGER dbo.trig_sysoriginatingservers_delete
ON dbo.sysoriginatingservers
FOR DELETE
AS
BEGIN
  SET NOCOUNT ON
  -- Only a single MSX server entry can exist in this table. ie. originating_server_id = 1 and master_server = 1. 
  IF((EXISTS (SELECT *
           FROM deleted AS d
                JOIN dbo.sysjobs AS j ON d.originating_server_id = j.originating_server_id)) OR
    (EXISTS (SELECT *
           FROM deleted AS d
                JOIN dbo.sysschedules AS s ON d.originating_server_id = s.originating_server_id)))
  BEGIN
    RAISERROR(14380, -1, -1)
   ROLLBACK TRANSACTION
    RETURN
  END
END
go


/**************************************************************/
/* sysoriginatingservers_view                                 */
/**************************************************************/
PRINT ''
PRINT 'Creating view sysoriginatingservers_view...'
GO
IF (NOT OBJECT_ID(N'dbo.sysoriginatingservers_view', 'V') IS NULL)
  DROP VIEW sysoriginatingservers_view
GO
CREATE VIEW dbo.sysoriginatingservers_view(originating_server_id, originating_server, master_server)
AS 
   SELECT
      0 AS originating_server_id, 
      UPPER(CONVERT(sysname, SERVERPROPERTY('ServerName'))) AS originating_server,
      0 AS master_server
   UNION
   SELECT 
      originating_server_id,
      originating_server,
      master_server
   FROM
      dbo.sysoriginatingservers
GO

/**************************************************************/
/* SYSJOBS                                                    */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobs')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobs...'

  CREATE TABLE sysjobs
  (
  job_id                     UNIQUEIDENTIFIER NOT NULL,
  originating_server_id      INT              NOT NULL, -- REFERENCE enforced by trig_sysjobs_insert_update
  name                       sysname          NOT NULL,
  enabled                    TINYINT          NOT NULL,
  description                NVARCHAR(512)    NULL,
  start_step_id              INT              NOT NULL,
  category_id                INT              NOT NULL,
  owner_sid                  VARBINARY(85)    NOT NULL,
  notify_level_eventlog      INT              NOT NULL,
  notify_level_email         INT              NOT NULL,
  notify_level_netsend       INT              NOT NULL,
  notify_level_page          INT              NOT NULL,
  notify_email_operator_id   INT              NOT NULL,
  notify_netsend_operator_id INT              NOT NULL,
  notify_page_operator_id    INT              NOT NULL,
  delete_level               INT              NOT NULL,
  date_created               DATETIME         NOT NULL,
  date_modified              DATETIME         NOT NULL,
  version_number             INT              NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON sysjobs(job_id)
  CREATE NONCLUSTERED     INDEX nc1   ON sysjobs(name) -- NOTE: This is deliberately non-unique
  CREATE NONCLUSTERED     INDEX nc3   ON sysjobs(category_id)
  CREATE NONCLUSTERED     INDEX nc4   ON sysjobs(owner_sid)
END
go

/**************************************************************/
/* trig_sysjobs_insert_update                                 */
/**************************************************************/

PRINT ''
PRINT 'Creating trigger trig_sysjobs_insert_update...'

IF NOT OBJECT_ID('dbo.trig_sysjobs_insert_update', 'TR') IS NULL
    DROP TRIGGER dbo.trig_sysjobs_insert_update
GO
CREATE TRIGGER dbo.trig_sysjobs_insert_update
ON dbo.sysjobs
FOR INSERT, UPDATE
AS
BEGIN
  SET NOCOUNT ON
  -- Disallow the insert or update if the originating_server_id isn't in sysoriginatingservers_view.  
  IF (EXISTS (SELECT *
            FROM inserted
           WHERE inserted.originating_server_id NOT IN 
                    (SELECT v.originating_server_id 
                     FROM sysoriginatingservers_view AS v)))
  BEGIN
   RAISERROR(14379, -1, -1, 'dbo.sysjobs')
   ROLLBACK TRANSACTION
    RETURN
  END
END
go

/**************************************************************/
/* SYSJOBSERVERS                                              */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobservers')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobservers...'

  CREATE TABLE sysjobservers
  (
  job_id               UNIQUEIDENTIFIER NOT NULL,
  server_id            INT              NOT NULL,
  last_run_outcome     TINYINT          NOT NULL,
  last_outcome_message NVARCHAR(4000)   NULL,
  last_run_date        INT              NOT NULL,
  last_run_time        INT              NOT NULL,
  last_run_duration    INT              NOT NULL
  )

  CREATE CLUSTERED    INDEX clust ON sysjobservers(job_id)
  CREATE NONCLUSTERED INDEX nc1   ON sysjobservers(server_id)
END
ELSE
BEGIN
  ALTER TABLE sysjobservers ALTER COLUMN
    last_outcome_message NVARCHAR(4000)   NULL
END
go

/**************************************************************/
/* SYSJOBS_VIEW                                               */
/**************************************************************/

PRINT ''
PRINT 'Creating view sysjobs_view...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sysjobs_view')
              AND (type = 'V')))
  DROP VIEW sysjobs_view
go
CREATE VIEW sysjobs_view
AS
SELECT jobs.job_id,
       svr.originating_server,
       jobs.name,
       jobs.enabled,
       jobs.description,
       jobs.start_step_id,
       jobs.category_id,
       jobs.owner_sid,
       jobs.notify_level_eventlog,
       jobs.notify_level_email,
       jobs.notify_level_netsend,
       jobs.notify_level_page,
       jobs.notify_email_operator_id,
       jobs.notify_netsend_operator_id,
       jobs.notify_page_operator_id,
       jobs.delete_level,
       jobs.date_created,
       jobs.date_modified,
       jobs.version_number,
       jobs.originating_server_id,
       svr.master_server
FROM msdb.dbo.sysjobs as jobs
  JOIN msdb.dbo.sysoriginatingservers_view as svr
    ON jobs.originating_server_id = svr.originating_server_id
  --LEFT JOIN msdb.dbo.sysjobservers js ON jobs.job_id = js.job_id
WHERE (owner_sid = SUSER_SID())
   OR (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
   OR (ISNULL(IS_MEMBER(N'SQLAgentReaderRole'), 0) = 1)
   OR ( (ISNULL(IS_MEMBER(N'TargetServersRole'), 0) = 1) AND
        (EXISTS(SELECT * FROM msdb.dbo.sysjobservers js 
         WHERE js.server_id <> 0 AND js.job_id = jobs.job_id))) -- filter out local jobs  
go



IF (OBJECT_ID(N'dbo.syssessions', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table syssessions...'

   CREATE TABLE dbo.syssessions
   (
      session_id                INT  IDENTITY PRIMARY KEY,       
    agent_start_date          DATETIME NOT NULL    
   )
   CREATE UNIQUE NONCLUSTERED INDEX nonclust ON syssessions(agent_start_date)
END
go

IF (OBJECT_ID(N'dbo.sysjobactivity', 'U') IS NULL)
BEGIN
   PRINT ''
   PRINT 'Creating table sysjobactivity...'

   CREATE TABLE dbo.sysjobactivity
   (
      session_id                INT              NOT NULL REFERENCES syssessions(session_id),           
      job_id                    UNIQUEIDENTIFIER NOT NULL REFERENCES  sysjobs(job_id) ON DELETE CASCADE,           
    run_requested_date        DATETIME         NULL,
    run_requested_source      sysname          NULL,
    queued_date               DATETIME         NULL,
    start_execution_date      DATETIME         NULL,
    last_executed_step_id     INT              NULL,
    last_executed_step_date   DATETIME         NULL,
    stop_execution_date       DATETIME         NULL,
    job_history_id            INT              NULL,      --keeps a reference to the record in sysjobhistory for detailed job information
    next_scheduled_run_date   DATETIME         NULL
   )
   CREATE UNIQUE CLUSTERED    INDEX clust ON sysjobactivity(session_id, job_id)
END
go


/**************************************************************/
/* SYSJOBSTEPS                                                */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobsteps')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobsteps...'

  CREATE TABLE sysjobsteps
  (
  job_id                UNIQUEIDENTIFIER NOT NULL,
  step_id               INT              NOT NULL,
  step_name             sysname          NOT NULL,
  subsystem             NVARCHAR(40)    NOT NULL,
  command               NVARCHAR(max)    NULL,
  flags                 INT              NOT NULL,
  additional_parameters NTEXT            NULL,
  cmdexec_success_code  INT              NOT NULL,
  on_success_action     TINYINT          NOT NULL,
  on_success_step_id    INT              NOT NULL,
  on_fail_action        TINYINT          NOT NULL,
  on_fail_step_id       INT              NOT NULL,
  server                sysname          NULL,      -- Used only by replication and OLAP
  database_name         sysname          NULL,
  database_user_name    sysname          NULL,
  retry_attempts        INT              NOT NULL,
  retry_interval        INT              NOT NULL,
  os_run_priority       INT              NOT NULL,  -- NOTE: Cannot use TINYINT because we need a signed number
  output_file_name      NVARCHAR(200)    NULL,
  last_run_outcome      INT              NOT NULL,
  last_run_duration     INT              NOT NULL,
  last_run_retries      INT              NOT NULL,
  last_run_date         INT              NOT NULL,
  last_run_time         INT              NOT NULL,
  proxy_id              INT              NULL,
  step_uid              UNIQUEIDENTIFIER NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON sysjobsteps(job_id, step_id)
  CREATE UNIQUE NONCLUSTERED INDEX nc1 ON sysjobsteps(job_id, step_name)
  CREATE UNIQUE NONCLUSTERED INDEX nc2 ON sysjobsteps(step_uid)

END
go


/**************************************************************/
/* SYSJOBSTEPSLOGS                                                */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobstepslogs')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobstepslogs...'

  CREATE TABLE sysjobstepslogs
  (
  log_id                INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
  log                   NVARCHAR(max)    NOT NULL,
  date_created          DATETIME         NOT NULL DEFAULT getdate(),
  date_modified         DATETIME         NOT NULL DEFAULT getdate(),
  log_size              bigint           NOT NULL ,
  step_uid              UNIQUEIDENTIFIER NOT NULL REFERENCES  sysjobsteps(step_uid) ON DELETE CASCADE 
  )
END
go


/**************************************************************/
/* SYSSCHEDULES                                               */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysschedules')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysschedules...'

  CREATE TABLE sysschedules
  (
  schedule_id            INT IDENTITY     PRIMARY KEY CLUSTERED,
  schedule_uid           UNIQUEIDENTIFIER NOT NULL,
  originating_server_id  INT              NOT NULL, -- REFERENCE enforced by trig_sysschedules_insert_update
  name                   sysname          NOT NULL,
  owner_sid              varbinary(85)    NOT NULL, 
  enabled                INT              NOT NULL,
  freq_type              INT              NOT NULL,
  freq_interval          INT              NOT NULL,
  freq_subday_type       INT              NOT NULL,
  freq_subday_interval   INT              NOT NULL,
  freq_relative_interval INT              NOT NULL,
  freq_recurrence_factor INT              NOT NULL,
  active_start_date      INT              NOT NULL,
  active_end_date        INT              NOT NULL,
  active_start_time      INT              NOT NULL,
  active_end_time        INT              NOT NULL,
  date_created           DATETIME         NOT NULL  DEFAULT (GETDATE()),
  date_modified          DATETIME         NOT NULL  DEFAULT (GETDATE()),
  version_number         INT              NOT NULL  DEFAULT (1)
  )

  -- CREATE UNIQUE CLUSTERED INDEX clust ON sysschedules(job_id, name)
END
go

/**************************************************************/
/* trig_sysschedules_insert_update                            */
/**************************************************************/

PRINT ''
PRINT 'Creating trigger trig_sysschedules_insert_update...'

IF NOT OBJECT_ID('dbo.trig_sysschedules_insert_update', 'TR') IS NULL
    DROP TRIGGER dbo.trig_sysschedules_insert_update
GO
CREATE TRIGGER dbo.trig_sysschedules_insert_update
ON dbo.sysschedules
FOR INSERT, UPDATE
AS
BEGIN
  SET NOCOUNT ON
  -- Disallow the insert or update if the originating_server_id isn't in sysoriginatingservers_view. 
  IF (EXISTS (SELECT *
            FROM inserted
           WHERE inserted.originating_server_id NOT IN 
                    (SELECT v.originating_server_id 
                     FROM sysoriginatingservers_view AS v)))
  BEGIN
   RAISERROR(14379, -1, -1, 'dbo.sysschedules')
   ROLLBACK TRANSACTION
    RETURN
  END
END
go

/**************************************************************/
/* SYSSCHEDULES_LOCALSERVER_VIEW                              */
/**************************************************************/

PRINT ''
PRINT 'Creating view sysschedules_localserver_view...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sysschedules_localserver_view')
              AND (type = 'V')))
  DROP VIEW sysschedules_localserver_view
go
CREATE VIEW sysschedules_localserver_view
AS
SELECT sched.schedule_id,
       sched.schedule_uid,
       sched.originating_server_id,
       sched.name,
       sched.owner_sid,
       sched.enabled,
       sched.freq_type,
       sched.freq_interval,
       sched.freq_subday_type,
       sched.freq_subday_interval,
       sched.freq_relative_interval,
       sched.freq_recurrence_factor,
       sched.active_start_date,
       sched.active_end_date,
       sched.active_start_time,
       sched.active_end_time,
       sched.date_created,
       sched.date_modified,
       sched.version_number,
       svr.originating_server,
       svr.master_server
FROM msdb.dbo.sysschedules as sched
    JOIN msdb.dbo.sysoriginatingservers_view as svr
    ON sched.originating_server_id = svr.originating_server_id
WHERE (svr.master_server = 0)
  AND ( (sched.owner_sid = SUSER_SID())
        OR (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
      OR (ISNULL(IS_MEMBER(N'SQLAgentReaderRole'), 0) = 1)
      )
go


/**************************************************************/
/* SYSJOBSCHEDULES                                            */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysjobschedules')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysjobschedules...'

  CREATE TABLE sysjobschedules
  (
  schedule_id            INT              REFERENCES sysschedules(schedule_id),
  job_id                 UNIQUEIDENTIFIER REFERENCES sysjobs(job_id),
  next_run_date          INT              NOT NULL DEFAULT 0,
  next_run_time          INT              NOT NULL DEFAULT 0
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON sysjobschedules(job_id, schedule_id)
  CREATE NONCLUSTERED INDEX [NC_sysjobschedules_schedule_id] ON sysjobschedules(schedule_id)
END
go


/**************************************************************/
/* SYSCATEGORIES                                              */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'syscategories')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table syscategories...'

  CREATE TABLE syscategories
  (
  category_id    INT IDENTITY NOT NULL,
  category_class INT          NOT NULL, -- 1 = Job, 2 = Alert, 3 = Operator
  category_type  TINYINT      NOT NULL, -- 1 = Local, 2 = Multi-Server [Only relevant if class is 1; otherwise, 3 (None)]
  name           sysname      NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON syscategories(name, category_class)
END
go

-- Install standard [permanent] categories (reserved ID range is 0 - 99)
SET IDENTITY_INSERT msdb.dbo.syscategories ON

DELETE FROM msdb.dbo.syscategories
WHERE (category_id < 100)

-- Core categories
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 0, 1, 1, N'[Uncategorized (Local)]')        -- Local default
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 1, 1, 1, N'Jobs from MSX')                  -- All jobs downloaded from the MSX are placed in this category
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 2, 1, 2, N'[Uncategorized (Multi-Server)]') -- Multi-server default
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 3, 1, 1, N'Database Maintenance')           -- Default for all jobs created by the Maintenance Plan Wizard
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 5, 1, 1, N'Full-Text')                      -- Default for all jobs created by the Index Server
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 6, 1, 1, N'Log Shipping')                   -- Default for Log Shipping jobs
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 7, 1, 1, N'Database Engine Tuning Advisor') -- Default for DTA jobs
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES ( 8, 1, 1, N'Data Collector')                   -- Default for all jobs created by the Data Collector
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (98, 2, 3, N'[Uncategorized]')                -- Alert default
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (99, 3, 3, N'[Uncategorized]')                -- Operator default

-- Replication categories
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (10, 1, 1, N'REPL-Distribution')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (11, 1, 1, N'REPL-Distribution Cleanup')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (12, 1, 1, N'REPL-History Cleanup')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (13, 1, 1, N'REPL-LogReader')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (14, 1, 1, N'REPL-Merge')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (15, 1, 1, N'REPL-Snapshot')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (16, 1, 1, N'REPL-Checkup')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (17, 1, 1, N'REPL-Subscription Cleanup')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (18, 1, 1, N'REPL-Alert Response')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (19, 1, 1, N'REPL-QueueReader')
INSERT INTO msdb.dbo.syscategories (category_id, category_class, category_type, name) VALUES (20, 2, 3, N'Replication')

SET IDENTITY_INSERT msdb.dbo.syscategories OFF
go

/**************************************************************/
/* SYSTARGETSERVERS                                           */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'systargetservers')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table systargetservers...'

  CREATE TABLE systargetservers
  (
  server_id               INT IDENTITY  NOT NULL,
  server_name             sysname       NOT NULL,
  location                NVARCHAR(200) NULL,
  time_zone_adjustment    INT           NOT NULL,  -- The offset from GMT in minutes (set by sp_msx_enlist)
  enlist_date             DATETIME      NOT NULL,
  last_poll_date          DATETIME      NOT NULL,
  status                  INT           NOT NULL,  -- 1 = Normal, 2 = Offline, 4 = Blocked
  local_time_at_last_poll DATETIME      NOT NULL,  -- The local time at the target server as-of the last time it polled the MSX
  enlisted_by_nt_user     NVARCHAR(100) NOT NULL,
  poll_interval           INT           NOT NULL   -- The MSX polling interval (in seconds)
  )

  EXECUTE sys.sp_bindefault default_current_date, N'systargetservers.enlist_date'
  EXECUTE sys.sp_bindefault default_current_date, N'systargetservers.last_poll_date'
  EXECUTE sys.sp_bindefault default_one,          N'systargetservers.status'

  CREATE UNIQUE CLUSTERED    INDEX clust ON systargetservers(server_id)
  CREATE UNIQUE NONCLUSTERED INDEX nc1   ON systargetservers(server_name)
END
go

/**************************************************************/
/* SYSTARGETSERVERS_VIEW                                      */
/**************************************************************/

PRINT ''
PRINT 'Creating view systargetservers_view...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'systargetservers_view')
              AND (type = 'V')))
  DROP VIEW systargetservers_view
go
CREATE VIEW systargetservers_view
AS
SELECT server_id,
       server_name,
       enlist_date,
       last_poll_date
FROM msdb.dbo.systargetservers
UNION
SELECT 0,
       CONVERT(sysname, SERVERPROPERTY('ServerName')),
       CONVERT(DATETIME, N'19981113', 112),
       CONVERT(DATETIME, N'19981113', 112)
go

/**************************************************************/
/* SYSTARGETSERVERGROUPS                                      */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'systargetservergroups')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table systargetservergroups...'

  CREATE TABLE systargetservergroups
  (
  servergroup_id INT IDENTITY NOT NULL,
  name           sysname      NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON systargetservergroups(name)
END
go

/**************************************************************/
/* SYSTARGETSERVERGROUPMEMBERS                                */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'systargetservergroupmembers')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table systargetservergroupmembers...'

  CREATE TABLE systargetservergroupmembers
  (
  servergroup_id INT NOT NULL,
  server_id      INT NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX clust ON systargetservergroupmembers(servergroup_id, server_id)
  CREATE NONCLUSTERED     INDEX nc1   ON systargetservergroupmembers(server_id)
END
go

/**************************************************************/
/* SYSALERTS                                                  */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysalerts')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysalerts...'

  CREATE TABLE sysalerts
  (
  id                        INT IDENTITY     NOT NULL,
  name                      sysname          NOT NULL, -- Was length 60 in 6.x
  event_source              NVARCHAR(100)    NOT NULL,
  event_category_id         INT              NULL,
  event_id                  INT              NULL,
  message_id                INT              NOT NULL, -- Was NULL in 6.x
  severity                  INT              NOT NULL, -- Was NULL in 6.x
  enabled                   TINYINT          NOT NULL,
  delay_between_responses   INT              NOT NULL,
  last_occurrence_date      INT              NOT NULL, -- Was NULL in 6.x
  last_occurrence_time      INT              NOT NULL, -- Was NULL in 6.x
  last_response_date        INT              NOT NULL, -- Was NULL in 6.x
  last_response_time        INT              NOT NULL, -- Was NULL in 6.x
  notification_message      NVARCHAR(512)    NULL,
  include_event_description TINYINT          NOT NULL,
  database_name             NVARCHAR(512)    NULL,
  event_description_keyword NVARCHAR(100)    NULL,
  occurrence_count          INT              NOT NULL,
  count_reset_date          INT              NOT NULL, -- Was NULL in 6.x
  count_reset_time          INT              NOT NULL, -- Was NULL in 6.x
  job_id                    UNIQUEIDENTIFIER NOT NULL, -- Was NULL in 6.x
  has_notification          INT              NOT NULL, -- New for 7.0
  flags                     INT              NOT NULL, -- Was NULL in 6.x
  performance_condition     NVARCHAR(512)    NULL,
  category_id               INT              NOT NULL  -- New for 7.0
  )

  CREATE UNIQUE CLUSTERED INDEX ByName ON sysalerts(name)
  CREATE UNIQUE INDEX ByID ON sysalerts(id)
END
go

/**************************************************************/
/* SYSOPERATORS                                               */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysoperators')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysoperators...'

  CREATE TABLE sysoperators
  (
  id                        INT IDENTITY  NOT NULL,
  name                      sysname       NOT NULL, -- Was length 50 in 6.x
  enabled                   TINYINT       NOT NULL,
  email_address             NVARCHAR(100) NULL,
  last_email_date           INT           NOT NULL, -- Was NULL in 6.x
  last_email_time           INT           NOT NULL, -- Was NULL in 6.x
  pager_address             NVARCHAR(100) NULL,
  last_pager_date           INT           NOT NULL, -- Was NULL in 6.x
  last_pager_time           INT           NOT NULL, -- Was NULL in 6.x
  weekday_pager_start_time  INT           NOT NULL,
  weekday_pager_end_time    INT           NOT NULL,
  saturday_pager_start_time INT           NOT NULL,
  saturday_pager_end_time   INT           NOT NULL,
  sunday_pager_start_time   INT           NOT NULL,
  sunday_pager_end_time     INT           NOT NULL,
  pager_days                TINYINT       NOT NULL,
  netsend_address           NVARCHAR(100) NULL,     -- New for 7.0
  last_netsend_date         INT           NOT NULL, -- New for 7.0
  last_netsend_time         INT           NOT NULL, -- New for 7.0
  category_id               INT           NOT NULL  -- New for 7.0
  )

  CREATE UNIQUE CLUSTERED INDEX ByName ON sysoperators(name)
  CREATE UNIQUE INDEX ByID ON sysoperators(id)
END
go

/**************************************************************/
/* SYSNOTIFICATIONS                                           */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysnotifications')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysnotifications...'

  CREATE TABLE sysnotifications
  (
  alert_id             INT      NOT NULL,
  operator_id          INT      NOT NULL,
  notification_method  TINYINT  NOT NULL
  )

  CREATE UNIQUE CLUSTERED INDEX ByAlertIDAndOperatorID ON sysnotifications(alert_id, operator_id)
END
go



/**************************************************************/
/*                                                            */
/*  M  A  I  N  T  E  N  A  N  C  E    P  L  A  N  S          */
/*                                                            */
/**************************************************************/

/**************************************************************/
/* sysmaintplan_subplans                                      */
/**************************************************************/
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysmaintplan_subplans')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysmaintplan_subplans...'

    -- This table stores the DTS package associated with the maintenance plan
    -- It also stored metadata about the maintenance plan such as its name, description etc
    CREATE TABLE sysmaintplan_subplans
    (
        subplan_id          UNIQUEIDENTIFIER    NOT NULL 
            CONSTRAINT [PK_sysmaintplan_subplan] PRIMARY KEY CLUSTERED,
        subplan_name        sysname             NOT NULL,
        subplan_description NVARCHAR(512)       NULL,
        plan_id             UNIQUEIDENTIFIER    NOT NULL,
        job_id              UNIQUEIDENTIFIER    NOT NULL 
            CONSTRAINT FK_subplan_job_id
            FOREIGN KEY (job_id) REFERENCES sysjobs(job_id),
        msx_job_id          UNIQUEIDENTIFIER DEFAULT NULL NULL
            CONSTRAINT FK_subplan_msx_job_id
            FOREIGN KEY (msx_job_id) REFERENCES sysjobs(job_id),
        schedule_id         INT                 NULL 
            CONSTRAINT FK_subplan_schedule_id 
            FOREIGN KEY (schedule_id) REFERENCES sysschedules(schedule_id),
        msx_plan bit DEFAULT 0 NOT NULL
    )
END
go

/**************************************************************/
/* sysmaintplan_log                                           */
/**************************************************************/
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysmaintplan_log')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysmaintplan_log...'

    -- This table stores the maintenance plan log info 
    CREATE TABLE sysmaintplan_log
    (
        task_detail_id  UNIQUEIDENTIFIER    NOT NULL 
            CONSTRAINT [PK_sysmaintplan_taskdetail_id] PRIMARY KEY CLUSTERED,
        plan_id         UNIQUEIDENTIFIER    NULL,
        subplan_id      UNIQUEIDENTIFIER    NULL 
            CONSTRAINT [FK_sysmaintplan_log_subplan_id] 
            FOREIGN KEY (subplan_id) REFERENCES sysmaintplan_subplans(subplan_id),
        start_time      DATETIME            NULL,
        end_time        DATETIME            NULL,
        succeeded       BIT                 NULL,
        logged_remotely bit not null default (0),
        source_server_name nvarchar (128) NULL,
        plan_name nvarchar (128) NULL,
        subplan_name nvarchar (128) NULL
    )
END
go


/**************************************************************/
/* sysmaintplan_logdetail                                     */
/**************************************************************/
IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'sysmaintplan_logdetail')
                  AND (type = 'U')))
BEGIN
  PRINT ''
  PRINT 'Creating table sysmaintplan_logdetail...'

    -- This table stores the maintenance plan log details 
    CREATE TABLE sysmaintplan_logdetail
    (
        task_detail_id  UNIQUEIDENTIFIER NOT NULL 
            CONSTRAINT [FK_sysmaintplan_log_detail_task_id] 
            FOREIGN KEY (task_detail_id) REFERENCES sysmaintplan_log(task_detail_id)
            ON DELETE CASCADE,
        line1           NVARCHAR(256)   NOT NULL,
        line2           NVARCHAR(256)   NULL,
        line3           NVARCHAR(256)   NULL,
        line4           NVARCHAR(256)   NULL,
        line5           NVARCHAR(256)   NULL,
        server_name     sysname         NOT NULL,
        start_time      DATETIME        NULL,
        end_time        DATETIME        NULL,
        error_number    INT             NULL,
        error_message   NVARCHAR(max)   NULL,
        command         NVARCHAR(max)   NULL,
        succeeded       BIT             NULL
    )
END
go


/**************************************************************/
/* SYSTASKIDS                                                 */
/*                                                            */
/* This table provides a mapping between new GUID job ID's    */
/* and 6.x INT task ID's.                                     */
/* Entries are made in this table for all existing 6.x tasks  */
/* and for all new tasks added using the 7.0 version of       */
/* sp_addtask.                                                */
/* Callers of the 7.0 version of sp_helptask will ONLY see    */
/* tasks [jobs] that have a corresponding entry in this table */
/* [IE. Jobs created with sp_add_job will not be returned].   */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'systaskids')
                  AND (type = 'U')))
BEGIN
  CREATE TABLE systaskids
  (
  task_id INT IDENTITY     NOT NULL,
  job_id  UNIQUEIDENTIFIER NOT NULL
  )

  CREATE CLUSTERED INDEX clust ON systaskids(job_id)
END
go

/**************************************************************/
/* SYSCACHEDCREDENTIALS                                       */
/*                                                            */
/**************************************************************/

IF (NOT EXISTS (SELECT *
                FROM msdb.dbo.sysobjects
                WHERE (name = N'syscachedcredentials')
                  AND (type = 'U')))
BEGIN
  CREATE TABLE syscachedcredentials
  (
  login_name          sysname      COLLATE database_default NOT NULL PRIMARY KEY,
  has_server_access   BIT          NOT NULL DEFAULT 0,
  is_sysadmin_member  BIT          NOT NULL DEFAULT 0,
  cachedate           DATETIME     NOT NULL DEFAULT getdate()
  )
END
go

---------------------------------------------------------------
-- Replication Datatype mapping tables
---------------------------------------------------------------

exec sys.sp_MSrepl_createdatatypemappings
go


CHECKPOINT
go

/**************************************************************/
/*                                                            */
/*        C  O  R  E     P  R  O  C  E  D  U  R  E  S         */
/*                                                            */
/**************************************************************/

PRINT ''
PRINT 'Creating function SQLAGENT_SUSER_SNAME ...'
IF (NOT OBJECT_ID(N'dbo.SQLAGENT_SUSER_SNAME', 'FN') IS NULL)
  DROP FUNCTION dbo.SQLAGENT_SUSER_SNAME
go

CREATE FUNCTION dbo.SQLAGENT_SUSER_SNAME(@user_sid VARBINARY(85)) RETURNS sysname
AS
BEGIN
  DECLARE @ret sysname
  IF @user_sid = 0xFFFFFFFF
    SELECT @ret = N'$(SQLAgentAccount)'
  ELSE
    SELECT @ret = SUSER_SNAME(@user_sid)
  RETURN @ret
END
go

PRINT ''
PRINT 'Creating function SQLAGENT_SUSER_SID ...'
IF (NOT OBJECT_ID(N'dbo.SQLAGENT_SUSER_SID', 'FN') IS NULL)
  DROP FUNCTION dbo.SQLAGENT_SUSER_SID
go

CREATE FUNCTION dbo.SQLAGENT_SUSER_SID(@user_name sysname) RETURNS VARBINARY(85)
AS
BEGIN
  DECLARE @ret VARBINARY(85)
  IF @user_name = N'$(SQLAgentAccount)'
    SELECT @ret = 0xFFFFFFFF
  ELSE
    SELECT @ret = SUSER_SID(@user_name, 0)
  RETURN @ret
END
go

-----------------------------------------------------------
-- get_principal_id : retrieves principal_id for a given sid
--
-----------------------------------------------------------
IF NOT OBJECT_ID('dbo.get_principal_id', 'FN') IS NULL
    DROP FUNCTION dbo.get_principal_id
GO

CREATE FUNCTION dbo.get_principal_id(@principal_sid varbinary(85))
RETURNS int
AS
BEGIN
    DECLARE @principal_id int
    SELECT @principal_id=principal_id FROM msdb.sys.database_principals WHERE sid=@principal_sid
    RETURN @principal_id
END
GO

-----------------------------------------------------------
-- get_principal_sid : retrieves principal sid from principal_id 
--
-----------------------------------------------------------
IF NOT OBJECT_ID('dbo.get_principal_sid', 'FN') IS NULL
    DROP FUNCTION dbo.get_principal_sid
GO

CREATE FUNCTION dbo.get_principal_sid(@principal_id int)
RETURNS varbinary(85)
AS
BEGIN
    DECLARE @principal_sid varbinary(85)
    SELECT @principal_sid=sid FROM msdb.sys.database_principals WHERE principal_id=@principal_id
    RETURN @principal_sid
END
GO
/**************************************************************/
/* SP_SQLAGENT_IS_SRVROLEMEMBER                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure SP_SQLAGENT_IS_SRVROLEMEMBER...'
IF (NOT OBJECT_ID(N'dbo.sp_sqlagent_is_srvrolemember', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_sqlagent_is_srvrolemember
go

CREATE PROCEDURE sp_sqlagent_is_srvrolemember
   @role_name sysname, @login_name sysname
AS
BEGIN
  DECLARE @is_member        INT
  SET NOCOUNT ON
  
  IF @role_name IS NULL OR @login_name IS NULL
    RETURN(0)
  
  SELECT @is_member = 0
  --IS_SRVROLEMEMBER works only if the login to be tested is provisioned with sqlserver
  if( @login_name = SUSER_SNAME())
    SELECT @is_member = IS_SRVROLEMEMBER(@role_name)
  else
    SELECT @is_member = IS_SRVROLEMEMBER(@role_name, @login_name)
    
  
  --try to impersonate. A try catch is used because we can have @name as NT groups also
  IF @is_member IS NULL
  BEGIN
    BEGIN TRY
      if( is_srvrolemember('sysadmin') = 1)
      begin
      EXECUTE AS LOGIN = @login_name -- impersonate 
        SELECT @is_member = IS_SRVROLEMEMBER(@role_name)  -- check role membership 
      REVERT -- revert back
      end
    END TRY
    BEGIN CATCH
      SELECT @is_member = 0
    END CATCH
  END
 
  RETURN ISNULL(@is_member,0)
END
go

/**************************************************************/
/* SP_VERIFY_CATEGORY_IDENTIFIERS                                */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_category_identifiers...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_category_identifiers', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_category_identifiers
go

CREATE PROCEDURE sp_verify_category_identifiers
   @name_of_name_parameter [varchar](60),
   @name_of_id_parameter [varchar](60),
   @category_name [sysname] OUTPUT,
   @category_id [INT] OUTPUT
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @category_id_as_char NVARCHAR(36)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @category_name          = LTRIM(RTRIM(@category_name))

  IF (@category_name = N'') SELECT @category_name = NULL

  IF ((@category_name IS NOT NULL) AND (@category_id IS NOT NULL))
  BEGIN
    RAISERROR(14524, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check category id
  IF (@category_id IS NOT NULL)
  BEGIN
    SELECT @category_name = name
    FROM msdb.dbo.syscategories
    WHERE (category_id = @category_id)
    IF (@category_name IS NULL)
    BEGIN
     SELECT @category_id_as_char = CONVERT(nvarchar(36), @category_id)
      RAISERROR(14262, -1, -1, '@category_id', @category_id_as_char)
      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check category name
  IF (@category_name IS NOT NULL)
  BEGIN
    -- The name is not ambiguous, so get the corresponding category_id (if the job exists)
    SELECT @category_id = category_id
    FROM msdb.dbo.syscategories
    WHERE (name = @category_name)
    IF (@category_id IS NULL)
    BEGIN
      RAISERROR(14262, -1, -1, '@category_name', @category_name)
      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go

PRINT ''
PRINT 'Creating function agent_datetime...'
IF (NOT OBJECT_ID(N'dbo.agent_datetime', 'FN') IS NULL)
  DROP FUNCTION dbo.agent_datetime
go

CREATE FUNCTION agent_datetime(@date int, @time int)
RETURNS DATETIME
AS
BEGIN
 RETURN
  (
    CONVERT(DATETIME,
          CONVERT(NVARCHAR(4),@date / 10000) + N'-' + 
          CONVERT(NVARCHAR(2),(@date % 10000)/100)  + N'-' +
          CONVERT(NVARCHAR(2),@date % 100) + N' ' +        
          CONVERT(NVARCHAR(2),@time / 10000) + N':' +        
          CONVERT(NVARCHAR(2),(@time % 10000)/100) + N':' +        
          CONVERT(NVARCHAR(2),@time % 100),
    120)
  )
END
go

/**************************************************************/
/* SP_VERIFY_PROXY_IDENTIFIERS                                */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_proxy_identifiers...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_proxy_identifiers', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_proxy_identifiers
go

CREATE PROCEDURE sp_verify_proxy_identifiers
   @name_of_name_parameter [varchar](60),
   @name_of_id_parameter [varchar](60),
   @proxy_name [sysname] OUTPUT,
   @proxy_id [INT] OUTPUT
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @proxy_id_as_char NVARCHAR(36)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @proxy_name             = LTRIM(RTRIM(@proxy_name))

  IF (@proxy_name = N'') SELECT @proxy_name = NULL

  IF ((@proxy_name IS NULL)     AND (@proxy_id IS NULL)) OR
     ((@proxy_name IS NOT NULL) AND (@proxy_id IS NOT NULL))
  BEGIN
    RAISERROR(14524, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check proxy id
  IF (@proxy_id IS NOT NULL)
  BEGIN
    SELECT @proxy_name = name
    FROM msdb.dbo.sysproxies
    WHERE (proxy_id = @proxy_id)
    IF (@proxy_name IS NULL)
    BEGIN
     SELECT @proxy_id_as_char = CONVERT(nvarchar(36), @proxy_id)
      RAISERROR(14262, -1, -1, '@proxy_id', @proxy_id_as_char)
      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check proxy name
  IF (@proxy_name IS NOT NULL)
  BEGIN
    -- The name is not ambiguous, so get the corresponding proxy_id (if the job exists)
    SELECT @proxy_id = proxy_id
    FROM msdb.dbo.sysproxies
    WHERE (name = @proxy_name)
    IF (@proxy_id IS NULL)
    BEGIN
      RAISERROR(14262, -1, -1, '@proxy_name', @proxy_name)
      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_VERIFY_CREDENTIAL_IDENTIFIERS                           */
/**************************************************************/
PRINT ''
PRINT 'Creating procedure sp_verify_credential_identifiers...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_credential_identifiers', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_credential_identifiers
go

CREATE PROCEDURE sp_verify_credential_identifiers
   @name_of_name_parameter [varchar](60),
   @name_of_id_parameter [varchar](60),
   @credential_name [sysname] OUTPUT,
   @credential_id [INT] OUTPUT
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @credential_id_as_char NVARCHAR(36)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @credential_name        = LTRIM(RTRIM(@credential_name))

  IF (@credential_name = N'') SELECT @credential_name = NULL

  IF ((@credential_name IS NULL)     AND (@credential_id IS NULL)) OR
     ((@credential_name IS NOT NULL) AND (@credential_id IS NOT NULL))
  BEGIN
    RAISERROR(14524, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check credential_id
  IF (@credential_id IS NOT NULL)
  BEGIN
    SELECT @credential_name = name
    FROM master.sys.credentials
    WHERE (credential_id = @credential_id)
    IF (@credential_name IS NULL)
    BEGIN
     SELECT @credential_id_as_char = CONVERT(nvarchar(36), @credential_id)
      RAISERROR(14262, -1, -1, '@credential_id', @credential_id_as_char)
      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check proxy name
  IF (@credential_name IS NOT NULL)
  BEGIN
    -- The name is not ambiguous, so get the corresponding credential_id (if the job exists)
    SELECT @credential_id = credential_id
    FROM master.sys.credentials
    WHERE (name = @credential_name)
    IF (@credential_id IS NULL)
    BEGIN
      RAISERROR(14262, -1, -1, '@credential_name', @credential_name)
      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go


/**************************************************************/
/* sp_verify_subsystems                                       */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_subsystems...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_subsystems', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_subsystems
go

CREATE PROCEDURE dbo.sp_verify_subsystems
   @syssubsytems_refresh_needed BIT = 0
AS
BEGIN
  SET NOCOUNT ON
   
  DECLARE @retval         INT
  DECLARE @InstRootPath nvarchar(512)
  DECLARE @VersionRootPath nvarchar(512)
  DECLARE @ComRootPath nvarchar(512)
  DECLARE @DtsRootPath nvarchar(512)
  DECLARE @SQLPSPath nvarchar(512)
  DECLARE @DTExec nvarchar(512)
  DECLARE @DTExecExists INT
  DECLARE @ToolsPath nvarchar(512)

  IF ( (@syssubsytems_refresh_needed=1) OR (NOT EXISTS(select * from syssubsystems)) )
  BEGIN
     EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'SQLPath', @InstRootPath OUTPUT
     IF @InstRootPath IS NULL
     BEGIN
       RAISERROR(14658, -1, -1) WITH LOG
       RETURN (1)
     END
     SELECT @InstRootPath = @InstRootPath + N'\binn\'

     EXEC master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\Microsoft Sql Server\100', N'VerSpecificRootDir', @VersionRootPath OUTPUT
     IF @VersionRootPath IS NULL
     BEGIN
       RAISERROR(14659, -1, -1) WITH LOG
       RETURN(1)
     END

     EXEC master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\Microsoft SQL Server\100\SSIS\Setup\DTSPath', N'', @DtsRootPath OUTPUT, N'no_output'
     IF (@DtsRootPath IS NOT NULL)
     BEGIN
       SELECT @DtsRootPath  = @DtsRootPath  + N'Binn\'
       SELECT @DTExec = @DtsRootPath + N'DTExec.exe'
       CREATE TABLE #t (file_exists int, is_directory int, parent_directory_exists int)
       INSERT #t EXEC xp_fileexist @DTExec
       SELECT TOP 1 @DTExecExists=file_exists from #t
       DROP TABLE #t
       IF ((@DTExecExists IS NULL) OR (@DTExecExists = 0))
         SET @DtsRootPath = NULL
     END

     SELECT @ComRootPath  = @VersionRootPath  + N'COM\'

     create table #Platform(ID int,  Name  sysname, Internal_Value int NULL, Value nvarchar(512))
     insert #Platform exec master.dbo.xp_msver 'Platform'
     if EXISTS(select * from #Platform where Value like '%64%')
     EXEC master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Wow6432Node\Microsoft\Microsoft Sql Server\100\Tools\ClientSetup', N'SQLPath', @ToolsPath OUTPUT
  else
     EXEC master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\Microsoft Sql Server\100\Tools\ClientSetup', N'SQLPath', @ToolsPath OUTPUT
     drop table #Platform
     SELECT @SQLPSPath  = @ToolsPath  + N'\Binn\SQLPS.exe'
     
     -- Procedure must start its own transaction if we don't have one already.
     DECLARE @TranCounter INT;
     SET @TranCounter = @@TRANCOUNT;
     IF @TranCounter = 0
     BEGIN
        BEGIN TRANSACTION;
     END

     -- Obtain processor count to determine maximum number of threads per subsystem
     DECLARE @xp_results TABLE
     (
     id              INT           NOT NULL,
     name            NVARCHAR(30)  COLLATE database_default NOT NULL,
     internal_value  INT           NULL,
     character_value NVARCHAR(212) COLLATE database_default NULL
     )
     INSERT INTO @xp_results
     EXECUTE master.dbo.xp_msver

     DECLARE @processor_count INT
     SELECT @processor_count = internal_value from @xp_results where id=16 -- ProcessorCount

     -- Modify database.
     BEGIN TRY

       --create subsystems
       --TSQL subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'TSQL')
       INSERT syssubsystems
       VALUES
       (
          1, N'TSQL',14556, FORMATMESSAGE(14557), FORMATMESSAGE(14557), FORMATMESSAGE(14557), FORMATMESSAGE(14557), FORMATMESSAGE(14557), 20 * @processor_count
       )
       --ActiveScripting subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'ActiveScripting')
       INSERT syssubsystems
       VALUES
       (
          2, N'ActiveScripting',  14555, @InstRootPath + N'SQLATXSS.DLL',NULL,N'ActiveScriptStart',N'ActiveScriptEvent',N'ActiveScriptStop', 10 * @processor_count
       )

       --CmdExec subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'CmdExec')
       INSERT syssubsystems
       VALUES
       (
          3, N'CmdExec', 14550, @InstRootPath + N'SQLCMDSS.DLL',NULL,N'CmdExecStart',N'CmdEvent',N'CmdExecStop', 10 * @processor_count
       )

       --Snapshot subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'Snapshot')
       INSERT syssubsystems
       VALUES
       (
          4, N'Snapshot',   14551, @InstRootPath + N'SQLREPSS.DLL', @ComRootPath + N'SNAPSHOT.EXE', N'ReplStart',N'ReplEvent',N'ReplStop',100 * @processor_count
       )

       --LogReader subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'LogReader')
       INSERT syssubsystems
       VALUES
       (
          5, N'LogReader',  14552, @InstRootPath + N'SQLREPSS.DLL', @ComRootPath + N'logread.exe',N'ReplStart',N'ReplEvent',N'ReplStop',25 * @processor_count
       )

       --Distribution subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'Distribution')
       INSERT syssubsystems
       VALUES
       (
          6, N'Distribution',  14553, @InstRootPath + N'SQLREPSS.DLL', @ComRootPath + N'DISTRIB.EXE',N'ReplStart',N'ReplEvent',N'ReplStop',100 * @processor_count
       )

       --Merge subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'Merge')
       INSERT syssubsystems
       VALUES
       (
          7, N'Merge',   14554, @InstRootPath + N'SQLREPSS.DLL',@ComRootPath + N'REPLMERG.EXE',N'ReplStart',N'ReplEvent',N'ReplStop',100 * @processor_count
       )

       --QueueReader subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'QueueReader')
       INSERT syssubsystems
       VALUES
       (
          8, N'QueueReader',   14581, @InstRootPath + N'SQLREPSS.dll',@ComRootPath + N'qrdrsvc.exe',N'ReplStart',N'ReplEvent',N'ReplStop',100 * @processor_count
       )

       --ANALYSISQUERY subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'ANALYSISQUERY')
       INSERT syssubsystems
       VALUES
       (
          9, N'ANALYSISQUERY', 14513, @InstRootPath + N'SQLOLAPSS.DLL',NULL,N'OlapStart',N'OlapQueryEvent',N'OlapStop',100 * @processor_count
       )

       --ANALYSISCOMMAND subsystem
       IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'ANALYSISCOMMAND')
       INSERT syssubsystems
       VALUES
       (
          10, N'ANALYSISCOMMAND', 14514, @InstRootPath + N'SQLOLAPSS.DLL',NULL,N'OlapStart',N'OlapCommandEvent',N'OlapStop',100 * @processor_count
       )

       IF(@DtsRootPath IS NOT NULL)
       BEGIN
          --DTS subsystem
          IF (NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'SSIS') )
             INSERT syssubsystems
             VALUES
             (
                11, N'SSIS', 14538, @InstRootPath + N'SQLDTSSS.DLL',@DtsRootPath + N'DTExec.exe',N'DtsStart',N'DtsEvent',N'DtsStop',100 * @processor_count
             )
          ELSE
             UPDATE syssubsystems SET agent_exe = @DtsRootPath + N'DTExec.exe' WHERE subsystem = N'SSIS'
       END
       ELSE
       BEGIN
          IF EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'SSIS')
            DELETE FROM syssubsystems WHERE subsystem = N'SSIS' 
       END
       
       --PowerShell subsystem     
	   IF NOT EXISTS(SELECT * FROM syssubsystems WHERE subsystem = N'PowerShell')
	   INSERT syssubsystems
	   VALUES
	   (
		  12, N'PowerShell', 14698, @InstRootPath + N'SQLPOWERSHELLSS.DLL', @SQLPSPath, N'PowerShellStart',N'PowerShellEvent',N'PowerShellStop',2
	   )
	   

   END TRY
   BEGIN CATCH

       DECLARE @ErrorMessage NVARCHAR(400)
       DECLARE @ErrorSeverity INT
       DECLARE @ErrorState INT

       SELECT @ErrorMessage = ERROR_MESSAGE()
       SELECT @ErrorSeverity = ERROR_SEVERITY()
       SELECT @ErrorState = ERROR_STATE()

       -- Roll back the transaction that we started if we are not nested
       IF @TranCounter = 0
       BEGIN
         ROLLBACK TRANSACTION;
       END
       -- if we are nested inside another transaction just raise the 
       -- error and let the outer transaction do the rollback
       RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   )
       RETURN (1)                  
     END CATCH
  END --(NOT EXISTS(select * from syssubsystems))
  
  -- commit the transaction we started
  IF @TranCounter = 0
  BEGIN
    COMMIT TRANSACTION;
  END
  
  RETURN(0) -- Success
END
go


/**************************************************************/
/* sp_verify_subsystem_identifiers                            */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_subsystem_identifiers...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_subsystem_identifiers', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_subsystem_identifiers
go

CREATE PROCEDURE dbo.sp_verify_subsystem_identifiers
   @name_of_name_parameter [varchar](60),
   @name_of_id_parameter [varchar](60),
   @subsystem_name [sysname] OUTPUT,
   @subsystem_id [INT] OUTPUT
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @subsystem_id_as_char NVARCHAR(36)

  SET NOCOUNT ON

  -- this call will populate subsystems table if necessary
  EXEC @retval = msdb.dbo.sp_verify_subsystems
  IF @retval <> 0
     RETURN(@retval)

  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @subsystem_name         = LTRIM(RTRIM(@subsystem_name))

  IF (@subsystem_name = N'') SELECT @subsystem_name = NULL

  IF ((@subsystem_name IS NULL)     AND (@subsystem_id IS NULL)) OR
     ((@subsystem_name IS NOT NULL) AND (@subsystem_id IS NOT NULL))
  BEGIN
    RAISERROR(14524, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check subsystem_id
  IF (@subsystem_id IS NOT NULL)
  BEGIN
    SELECT @subsystem_name = subsystem
    FROM msdb.dbo.syssubsystems
    WHERE (subsystem_id = @subsystem_id)
    IF (@subsystem_name IS NULL)
    BEGIN
     SELECT @subsystem_id_as_char = CONVERT(nvarchar(36), @subsystem_id)
      RAISERROR(14262, -1, -1, '@subsystem_id', @subsystem_id_as_char)
      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check subsystem name
  IF (@subsystem_name IS NOT NULL)
  BEGIN
    -- Make sure Dts is translated into new subsystem's name SSIS
    IF UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS) = N'DTS'
    BEGIN
      SET @subsystem_name = N'SSIS'
    END

    -- The name is not ambiguous, so get the corresponding subsystem_id (if the subsystem exists)
    SELECT @subsystem_id = subsystem_id
    FROM msdb.dbo.syssubsystems
    WHERE (UPPER(subsystem collate SQL_Latin1_General_CP1_CS_AS) = UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS))
    IF (@subsystem_id IS NULL)
    BEGIN
      RAISERROR(14262, -1, -1, '@subsystem_name', @subsystem_name)
      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* sp_verify_login_identifiers                                */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_login_identifiers...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_login_identifiers', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_login_identifiers
go

CREATE PROCEDURE dbo.sp_verify_login_identifiers
   @login_name [nvarchar](256),
   @fixed_server_role [nvarchar](256),
   @msdb_role [nvarchar](256),
   @name [nvarchar](256) OUTPUT,
  @sid  varbinary(85)   OUTPUT,
   @flags   INT OUTPUT
AS
BEGIN
   DECLARE @retval         INT
    DECLARE @raise_error    bit
   SET NOCOUNT ON

   SELECT @flags = -1, @raise_error = 0
  SELECT @sid = NULL

  IF @login_name IS NOT NULL 
   BEGIN
      --check validity
      --use the new optional parameter of SUSER_SID to have a case insensitive comparation for NT users
    SELECT @sid = SUSER_SID(@login_name, 0)
      IF @sid IS NULL
      BEGIN
         RAISERROR(14520, -1, -1, @login_name)
         RETURN(1) -- Failure    
      END
      SELECT @name = @login_name, @flags = 0
   END
  
   IF COALESCE(@login_name, @fixed_server_role, @msdb_role) IS NULL
   BEGIN
      RAISERROR(14519, -1, -1)
      RETURN(1) -- Failure    
   END

  IF @fixed_server_role IS NOT NULL  AND @flags <> -1
      SELECT @raise_error = 1
   ELSE IF @fixed_server_role IS NOT NULL
   --check validity
   BEGIN
      -- IS_SRVROLEMEMBER return NULL for an invalid server role
      IF ISNULL(IS_SRVROLEMEMBER(@fixed_server_role), -1) = -1
      BEGIN
         RAISERROR(14521, -1, -1, @fixed_server_role)
         RETURN(1) -- Failure    
      END   
      SELECT @name = @fixed_server_role, @flags = 1
    SELECT @sid = SUSER_SID(@fixed_server_role)
   END
   
  IF @msdb_role IS NOT NULL  AND @flags <> -1
      SELECT @raise_error = 1
   ELSE IF @msdb_role IS NOT NULL
   BEGIN
      --check the correctness of msdb role
      IF ISNULL(IS_MEMBER(@msdb_role), -1) = -1 
      BEGIN
         RAISERROR(14522, -1, -1, @msdb_role)
         RETURN(1) -- Failure    
      END      
      SELECT @sid = sid from sys.database_principals
      WHERE  UPPER(@msdb_role collate SQL_Latin1_General_CP1_CS_AS) = UPPER(name collate SQL_Latin1_General_CP1_CS_AS)
    AND type = 'R'
    IF @sid IS NULL
      BEGIN
         RAISERROR(14522, -1, -1, @msdb_role)
         RETURN(1) -- Failure    
      END      
      SELECT @name = @msdb_role, @flags = 2
   END

   IF    @raise_error = 1
   BEGIN
      RAISERROR(14519, -1, -1)
      RETURN(1) -- Failure    
   END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_VERIFY_PROXY                                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_proxy
go

CREATE PROCEDURE dbo.sp_verify_proxy
   @proxy_id [INT] = NULL,
   @proxy_name [sysname],
   @enabled [tinyint],
   @description [nvarchar](512) = NULL
AS
BEGIN
  DECLARE @return_code INT
  SET NOCOUNT ON

  -- Check if the NewName is unique
  IF (EXISTS ( SELECT *
               FROM msdb.dbo.sysproxies
               WHERE (name = @proxy_name) AND
            proxy_id <> ISNULL(@proxy_id,0) ))
  BEGIN
    RAISERROR(14261, 16, 1, '@name', @proxy_name)
    RETURN(1) -- Failure
  END

  -- Enabled must be 0 or 1
  IF (@enabled NOT IN (0, 1))
  BEGIN
    RAISERROR(14266, 16, 1, '@enabled', '0, 1')
    RETURN(1) -- Failure
  END
  
  RETURN(0)
END
go

/**************************************************************/
/* SP_ADD_PROXY                                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_add_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_add_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_add_proxy
go

CREATE PROCEDURE dbo.sp_add_proxy
   @proxy_name [sysname],
   @enabled [tinyint] = 1,
   @description [nvarchar](512) = NULL,
   @credential_name [sysname] = NULL,
  @credential_id [INT] = NULL,
   @proxy_id [int] = NULL OUTPUT
AS
BEGIN
  DECLARE @retval INT
  DECLARE @full_name NVARCHAR(257) --two sysnames + \
  DECLARE @user_sid VARBINARY(85)
  DECLARE @cred_date_time DATETIME
  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @proxy_name                = LTRIM(RTRIM(@proxy_name))
  SELECT @description               = LTRIM(RTRIM(@description))

  IF @proxy_name  = ''  SELECT @proxy_name  = NULL
  IF @description = ''  SELECT @description = NULL

  EXECUTE @retval = sp_verify_proxy NULL,
                                    @proxy_name,
                           @enabled,
                           @description

  IF (@retval <> 0)
     RETURN(1) -- Failure

   EXECUTE @retval = sp_verify_credential_identifiers '@credential_name',
                                                  '@credential_id',
                                                   @credential_name OUTPUT,
                                                   @credential_id   OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure
  -- warn if the user_domain\user_name does not exist
  SELECT @full_name = credential_identity, @cred_date_time = create_date from master.sys.credentials 
  WHERE  credential_id = @credential_id
  --force case insensitive comparation for NT users
  SELECT @user_sid = SUSER_SID(@full_name,0)
  IF @user_sid IS NULL
  BEGIN
    RAISERROR(14529, -1, -1, @full_name)
    RETURN(1)
  END

  -- Finally, do the actual INSERT
  INSERT INTO msdb.dbo.sysproxies
   (
      name,
    credential_id,
      enabled,
      description,
    user_sid,
    credential_date_created
   )
   VALUES
   (
      @proxy_name,
    @credential_id,
      @enabled,
      @description,
    @user_sid,
    @cred_date_time
   )
   
   --get newly created proxy_id;
   SELECT @proxy_id = SCOPE_IDENTITY()
END
go

/**************************************************************/
/* SP_DELETE_PROXY                                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_delete_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_delete_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_delete_proxy
go

CREATE PROCEDURE dbo.sp_delete_proxy
   @proxy_id      int = NULL,
   @proxy_name    sysname = NULL
   -- must specify only one of above parameters to identify the proxy
AS
BEGIN
   DECLARE @retval   INT
   SET NOCOUNT ON
    
   EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                  '@proxy_id',
                                                   @proxy_name OUTPUT,
                                                   @proxy_id   OUTPUT
    IF (@retval <> 0)
      RETURN(1) -- Failure

   --no jobsteps should use this proxy
   IF EXISTS (SELECT * FROM sysjobsteps 
            WHERE @proxy_id = proxy_id)
   BEGIN
      RAISERROR(14518, -1, -1, @proxy_id)
      RETURN(1) -- Failure
   END

    BEGIN TRANSACTION
      --delete any association between subsystems and this proxy 
      DELETE sysproxysubsystem
      WHERE  proxy_id = @proxy_id
       
      --delete any association between logins and this proxy 
      DELETE sysproxylogin
      WHERE  proxy_id = @proxy_id

      -- delete the entry in sysproxies table
      DELETE sysproxies
      WHERE proxy_id = @proxy_id

    COMMIT
   RETURN(0)
END
go


/**************************************************************/
/* SP_UPDATE_PROXY                                            */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_update_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_update_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_update_proxy
go

CREATE PROCEDURE dbo.sp_update_proxy
   @proxy_id [int] = NULL,
   @proxy_name [sysname] = NULL, 
   -- must specify only one of above parameter identify the proxy
   @credential_name [sysname] = NULL,
   @credential_id [INT] = NULL,
   @new_name [sysname] = NULL,
   @enabled [tinyint] = NULL,
   @description [nvarchar](512) = NULL
AS
BEGIN
   DECLARE  @x_new_name [sysname] 
   DECLARE  @x_credential_id [int] 
   DECLARE  @x_enabled [tinyint] 
   DECLARE @x_description [nvarchar](512)
   DECLARE @x_credential_date_created [datetime]
   DECLARE @user_sid VARBINARY(85)
      DECLARE @full_name [sysname] --two sysnames + \
   DECLARE @retval   INT
   SET NOCOUNT ON
    
   EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                  '@proxy_id',
                                                   @proxy_name OUTPUT,
                                                   @proxy_id   OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure

  IF @credential_id IS NOT NULL OR @credential_name IS NOT NULL
  BEGIN
     EXECUTE @retval = sp_verify_credential_identifiers '@credential_name',
                                                    '@credential_id',
                                                    @credential_name OUTPUT,
                                                    @credential_id   OUTPUT
    IF (@retval <> 0)
      RETURN(1) -- Failure
  END

   -- Remove any leading/trailing spaces from parameters
   SELECT @new_name                = LTRIM(RTRIM(@new_name))
   SELECT @description             = LTRIM(RTRIM(@description))
  -- Turn [nullable] empty string parameters into NULLs
  IF @new_name      = '' SELECT @new_name = NULL
  IF @description    = '' SELECT @description = NULL

  -- Set the x_ (existing) variables
  SELECT    @x_new_name      = name,
    @x_credential_id = credential_id,
      @x_enabled       = enabled,
      @x_description   = description,
    @x_credential_date_created = credential_date_created
   FROM sysproxies
   WHERE proxy_id = @proxy_id

  --get the new date from credential table
  IF  (@credential_id IS NOT NULL)
    SELECT @x_credential_date_created = create_date FROM master.sys.credentials
    WHERE  credential_id = @credential_id
        
    -- Fill out the values for all non-supplied parameters from the existing values
   IF    (@new_name      IS NULL) SELECT   @new_name          =           @x_new_name                          
   IF (@credential_id IS NULL) SELECT   @credential_id     =           @x_credential_id                                    
   IF (@enabled       IS NULL) SELECT   @enabled           =           @x_enabled                                    
   IF (@description   IS NULL) SELECT   @description       =           @x_description            

  -- warn if the user_domain\user_name does not exist
  SELECT @full_name = credential_identity from master.sys.credentials 
  WHERE  credential_id = @credential_id
  
  --force case insensitive comparation for NT users
  SELECT @user_sid = SUSER_SID(@full_name, 0)
  IF @user_sid IS NULL
  BEGIN
    RAISERROR(14529, -1, -1, @full_name)
    RETURN(1)
  END
 
  -- Finally, do the actual UPDATE
  UPDATE msdb.dbo.sysproxies
   SET
   name     =  @new_name,
   credential_id  =  @credential_id,
   user_sid =  @user_sid,
   enabled     =  @enabled,
   description =  @description,
   credential_date_created = @x_credential_date_created  --@x_ is OK in this case
   WHERE proxy_id = @proxy_id
END
go

/**************************************************************/
/* SP_SQLAGENT_IS_MEMBER                                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sqlagent_is_member...'
IF (NOT OBJECT_ID(N'dbo.sp_sqlagent_is_member', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_sqlagent_is_member
go

-- check if a login is member of NT group\database role
--
-- if we specify a NT group SID @login_sid should be NOT NULL
--
-- if a @role_principal_id is specified, a NULL login is allowed
-- in this case we check if the msdb database user associated
-- with the current security context is member of the specified
-- msdb database role (this allows us to verify if a particular
-- msdb database loginless msdb user is member of that msdb role)
CREATE PROCEDURE dbo.sp_sqlagent_is_member
(
  @group_sid VARBINARY(85) = NULL,
   @role_principal_id  INT = NULL, 
   @login_sid VARBINARY(85)
) 
AS
BEGIN
   DECLARE @ret_success  INT
  DECLARE @login        NVARCHAR(256)
   DECLARE @impersonated INT
  DECLARE @group_name   NVARCHAR(256)
   SELECT   @ret_success = 0 --failure  
  SELECT  @impersonated = 0

  IF (@group_sid IS NOT NULL AND @login_sid IS NULL)
    RETURN(0)

  --a sysadmin can check for every user group membership
  IF (@login_sid IS NOT NULL) AND (ISNULL(IS_SRVROLEMEMBER('sysadmin'),0) = 1)
  BEGIN
    --get login name from principal_id
    SELECT @login = SUSER_SNAME(@login_sid)
    
    IF SUSER_SNAME() <> @login
    BEGIN
       --impersonate
        EXECUTE sp_setuserbylogin @login
      SELECT @impersonated = 1
    END
  END
  
  IF @group_sid IS NOT NULL
    SELECT @group_name = SUSER_SNAME(@group_sid)
  ELSE
    SELECT @group_name = USER_NAME(@role_principal_id)
        
   -- return success, if login is member of the group, and failure if group doesnt exist or login is not member of the group
   SELECT  @ret_success = ISNULL(IS_MEMBER(@group_name),0)

   --revert to self
  IF @impersonated = 1
         EXECUTE sp_setuserbylogin

   RETURN @ret_success
END 
go

/**************************************************************/
/* sp_verify_proxy_permissions                          */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_proxy_permissions...'
IF (NOT OBJECT_ID(N'dbo.sp_verify_proxy_permissions', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_verify_proxy_permissions
go
CREATE PROCEDURE dbo.sp_verify_proxy_permissions
   @subsystem_name sysname,
   @proxy_id      INT = NULL,
   @name       NVARCHAR(256) = NULL,
   @raise_error    INT = 1,
   @allow_disable_proxy INT = 0,
   @verify_special_account INT = 0,
   @check_only_read_perm INT = 0
AS 
BEGIN
  DECLARE @retval   INT
  DECLARE @granted_sid VARBINARY(85)
  DECLARE @is_member INT
  DECLARE @is_sysadmin BIT
  DECLARE @flags TINYINT
  DECLARE @enabled TINYINT
  DECLARE @name_sid VARBINARY(85)
  DECLARE @role_from_sid sysname
  DECLARE @name_from_sid sysname
  DECLARE @is_SQLAgentOperatorRole BIT
  DECLARE @check_only_subsystem BIT
  DECLARE proxy_subsystem CURSOR LOCAL
  FOR
    SELECT p.sid, p.flags
    FROM sysproxyloginsubsystem_view p, syssubsystems s
    WHERE p.proxy_id = @proxy_id AND p.subsystem_id = s.subsystem_id
        AND UPPER(s.subsystem collate SQL_Latin1_General_CP1_CS_AS) = 
            UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS)
   
  SET NOCOUNT ON
  SELECT @retval = 1

  IF @proxy_id IS NULL
    RETURN(0)

   -- TSQL subsystem prohibited
  IF (UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS) = N'TSQL')
  BEGIN
    RAISERROR(14517, -1, -1)
    RETURN(1) -- Failure
  END
   
  --check if the date stored inside proxy still exists and match the cred create_date inside proxy
  --otherwise the credential has been tempered from outside
  --if so, disable proxy and continue execution
  --only a sysadmin caller have cross database permissions but
  --when executing by sqlagent this check will be always performed
  IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) 
  BEGIN
    IF NOT EXISTS(SELECT * FROM sysproxies p JOIN master.sys.credentials c ON p.credential_id = c.credential_id
            WHERE p.proxy_id = @proxy_id AND p.credential_date_created = c.create_date AND enabled=1)
    BEGIN
        UPDATE sysproxies SET enabled=0 WHERE proxy_id = @proxy_id
    END
  END
  
  --if no login has been passed check permission against the caller 
  IF @name IS NULL
    SELECT @name = SUSER_SNAME()  
    
  --check if the proxy is disable and continue or not based on
  --allow_disable_proxy
  --allow creation of a job step with a disabled proxy but
  --sqlagent always call with @allow_disable_proxy = 0
  SELECT @enabled = enabled FROM sysproxies WHERE proxy_id = @proxy_id
  IF (@enabled = 0) AND (@allow_disable_proxy = 0)
  BEGIN
    RAISERROR(14537, -1, -1, @proxy_id)
    RETURN(2) -- Failure
  END

  --we need to check permission only against subsystem in following cases
  --1. @name is sysadmin
  --2. @name is member of SQLAgentOperatorRole and @check_only_read_perm=1
  --3. @verify_special_account =1
  --sysadmin and SQLAgentOperatorRole have permission to view all proxies
  IF (@verify_special_account = 1)
    SET @check_only_subsystem = 1  
  ELSE
  BEGIN
    EXEC @is_sysadmin = sp_sqlagent_is_srvrolemember N'sysadmin', @name 
    IF (@is_sysadmin = 1)
      SET @check_only_subsystem = 1  
    ELSE
    BEGIN
      EXEC @is_SQLAgentOperatorRole = sp_sqlagent_is_srvrolemember N'SQLAgentOperatorRole', @name -- check role membership 
      IF ((@is_SQLAgentOperatorRole = 1) AND (@check_only_read_perm = 1))
        SET @check_only_subsystem = 1 
    END
  END 
  
  IF (@check_only_subsystem = 1)
  BEGIN
    IF NOT EXISTS(SELECT * FROM sysproxysubsystem sp JOIN syssubsystems s ON sp.subsystem_id = s.subsystem_id
                  WHERE proxy_id = @proxy_id  AND UPPER(s.subsystem collate SQL_Latin1_General_CP1_CS_AS) = 
                     UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS))
    BEGIN
      IF (@raise_error <> 0)
      BEGIN
        RAISERROR(14516, -1, -1, @proxy_id, @subsystem_name, @name)
      END         
      RETURN(1) -- Failure     
    END
    RETURN(0)
  END
  
  --get SID from name; we verify if a login has permission to use a certain proxy
  --force case insensitive comparation for NT users
  SELECT @name_sid = SUSER_SID(@name, 0)

  --check first if name has been granted explicit permissions
  IF (@name_sid IS NOT NULL)
  BEGIN
      IF EXISTS(SELECT * FROM sysproxyloginsubsystem_view p, syssubsystems s
        WHERE p.proxy_id = @proxy_id AND p.subsystem_id = s.subsystem_id
            AND UPPER(s.subsystem collate SQL_Latin1_General_CP1_CS_AS) = 
                UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS)
            AND
        p.sid = @name_sid) -- name has been granted explicit permissions
      BEGIN
        RETURN(0)
      END
  END

  OPEN proxy_subsystem
  FETCH NEXT FROM proxy_subsystem INTO @granted_sid, @flags
  WHILE (@@fetch_status = 0 AND @retval = 1)
  BEGIN
    IF @flags = 0 AND @granted_sid IS NOT NULL AND @name_sid IS NOT NULL -- NT GROUP 
    BEGIN
        EXEC @is_member = sp_sqlagent_is_member @group_sid = @granted_sid, @login_sid = @name_sid 
        IF @is_member = 1
          SELECT @retval = 0
    END
    ELSE IF @flags = 2 AND @granted_sid IS NOT NULL -- MSDB role (@name_sid can be null in case of a loginless user member of msdb)
    BEGIN
        DECLARE @principal_id INT
        SET @principal_id = msdb.dbo.get_principal_id(@granted_sid)
        EXEC @is_member = sp_sqlagent_is_member @role_principal_id = @principal_id, @login_sid = @name_sid 
        IF @is_member = 1
          SELECT @retval = 0
    END
    ELSE IF (@flags = 1) AND @granted_sid IS NOT NULL AND @name_sid IS NOT NULL -- FIXED SERVER Roles
    BEGIN   
      -- we have to use impersonation to check for role membership
      SELECT @role_from_sid = SUSER_SNAME(@granted_sid)
      SELECT @name_from_sid = SUSER_SNAME(@name_sid)
      EXEC   @is_member = sp_sqlagent_is_srvrolemember @role_from_sid, @name_from_sid -- check role membership 

      IF @is_member = 1
        SELECT @retval = 0
    END

    IF @retval = 1
    BEGIN
        SELECT @granted_sid = NULL
        FETCH NEXT FROM proxy_subsystem INTO @granted_sid, @flags
    END
  END
  DEALLOCATE proxy_subsystem
  
  IF (@retval = 1 AND @raise_error <> 0)
  BEGIN
    RAISERROR(14516, -1, -1, @proxy_id, @subsystem_name, @name)
    RETURN(1) -- Failure
  END

   --0 is for success
   RETURN @retval
END
go

/**************************************************************/
/* SP_HELP_PROXY                                              */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_help_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_help_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_help_proxy
go

CREATE PROCEDURE dbo.sp_help_proxy
   @proxy_id          int           = NULL,
   @proxy_name      sysname       = NULL,
   @subsystem_name sysname       = NULL,
   @name           nvarchar(256) = NULL
AS
BEGIN
  DECLARE @retval INT
  DECLARE @subsystem_id INT
  DECLARE @cur_subsystem_name NVARCHAR(40)
  DECLARE @current_proxy_id INT
  DECLARE @not_have_permission INT
  DECLARE cur_proxy CURSOR LOCAL
  FOR
    SELECT p.proxy_id, s.subsystem
    FROM sysproxies p, syssubsystems s
    WHERE ISNULL(UPPER(@subsystem_name collate SQL_Latin1_General_CP1_CS_AS), 
        UPPER(s.subsystem collate SQL_Latin1_General_CP1_CS_AS) ) = 
        UPPER(s.subsystem collate SQL_Latin1_General_CP1_CS_AS) AND 
        s.subsystem_id <> 1 --last is TSQL subsystem
          
  -- this call will populate subsystems table if necessary
  EXEC @retval = msdb.dbo.sp_verify_subsystems
  IF @retval <> 0
     RETURN(1) --failure
     
  --create temp table with returned rows
  DECLARE @temp_proxy TABLE
   (
      proxy_id             INT  --used to identify a proxy
   )

  SET NOCOUNT ON

  SELECT @subsystem_id = NULL

  -- Remove any leading/trailing spaces from parameters
  SELECT @proxy_name       = LTRIM(RTRIM(@proxy_name))
  IF @proxy_name           = '' SELECT @proxy_name = NULL
  SELECT @subsystem_name   = LTRIM(RTRIM(@subsystem_name))
  IF @proxy_name           = '' SELECT @proxy_name = NULL
  SELECT @name             = LTRIM(RTRIM(@name))
  IF @name                 = '' SELECT @name = NULL

  IF (@proxy_id IS NOT NULL OR @proxy_name IS NOT NULL)
  BEGIN
    EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                        '@proxy_id',
                                        @proxy_name OUTPUT,
                                        @proxy_id   OUTPUT
    IF (@retval <> 0)
        RETURN(1) -- Failure
  END

  IF @subsystem_name IS NOT NULL 
  BEGIN
    EXECUTE @retval = sp_verify_subsystem_identifiers '@subsystem_name',
                                      '@subsystem_id',
                                      @subsystem_name OUTPUT,
                                      @subsystem_id   OUTPUT
    IF (@retval <> 0)
        RETURN(1) -- Failure
  END
    
  IF (@subsystem_name IS NOT NULL AND @name IS NULL) OR
    (@subsystem_name IS NULL AND @name IS NOT NULL)
  BEGIN
    RAISERROR(14532, -1, -1, '@subsystem_name', '@name')
    RETURN(1) -- Failure
  END   
  
  --only member of sysadmin and SQLAgentOperatorRole roles can see proxies granted to somebody else
  IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0) AND
      (ISNULL(IS_MEMBER(N'SQLAgentOperatorRole'), 0) = 0))
  BEGIN
    SELECT @name = SUSER_SNAME()
  END

  IF @name IS NOT NULL
  BEGIN
    OPEN cur_proxy
    FETCH NEXT FROM cur_proxy INTO @current_proxy_id, @cur_subsystem_name
    WHILE (@@fetch_status = 0)
    BEGIN
      --verify if supplied user have permission to use the current proxy for specified subsystem
      --disabled proxy should be shown as well
      IF NOT EXISTS(SELECT * FROM @temp_proxy WHERE proxy_id = @current_proxy_id)
      BEGIN
        EXECUTE @not_have_permission = sp_verify_proxy_permissions 
          @subsystem_name = @cur_subsystem_name, 
          @proxy_id = @current_proxy_id, 
          @name = @name, 
          @raise_error = 0, 
          @allow_disable_proxy = 1, 
          @verify_special_account = 0, 
          @check_only_read_perm = 1
        IF (@not_have_permission = 0) -- have permissions
            INSERT @temp_proxy VALUES(@current_proxy_id)
      END
      FETCH NEXT FROM cur_proxy INTO @current_proxy_id, @cur_subsystem_name
    END 
    CLOSE cur_proxy  
    DEALLOCATE cur_proxy
  END
  ELSE
    INSERT @temp_proxy SELECT proxy_id from sysproxies

  -- returns different result sets if caller is admin or not
  IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR
      (ISNULL(IS_MEMBER(N'SQLAgentOperatorRole'), 0) = 1))
  BEGIN
    SELECT p.proxy_id, 
          p.name, 
          c.credential_identity, 
          p.enabled, 
          p.description, 
          p.user_sid, 
          p.credential_id,
          CASE WHEN c.credential_id IS NULL THEN 0 ELSE 1 END as credential_identity_exists
    FROM sysproxies p LEFT JOIN master.sys.credentials c ON p.credential_id = c.credential_id  
                  JOIN @temp_proxy t ON p.proxy_id = t.proxy_id
              WHERE ISNULL(@proxy_id, p.proxy_id) = p.proxy_id 
  END
  ELSE
  BEGIN
    SELECT p.proxy_id, p.name, null as credential_identity, p.enabled, p.description, null as user_sid, p.credential_id, null as credential_identity_exists 
    FROM sysproxies p, @temp_proxy t
    WHERE  ISNULL(@proxy_id, p.proxy_id) = p.proxy_id AND
              p.proxy_id = t.proxy_id
  END

END
go

/**************************************************************/
/* sp_grant_proxy_to_subsystem                             */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_grant_proxy_to_subsystem...'
IF (NOT OBJECT_ID(N'dbo.sp_grant_proxy_to_subsystem', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_grant_proxy_to_subsystem
go
CREATE PROCEDURE dbo.sp_grant_proxy_to_subsystem
   @proxy_id      int = NULL,
   @proxy_name    sysname = NULL,
   -- must specify only one of above parameter to identify the proxy
   @subsystem_id  int = NULL,
   @subsystem_name sysname = NULL
   -- must specify only one of above parameter to identify the subsystem
AS
BEGIN
   DECLARE @retval   INT
   DECLARE @proxy_account sysname
   SET NOCOUNT ON

   -- Remove any leading/trailing spaces from parameters
   SELECT @subsystem_name          = LTRIM(RTRIM(@subsystem_name))
   SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))

  -- Turn [nullable] empty string parameters into NULLs
  IF @subsystem_name    = '' SELECT @subsystem_name = NULL
  IF @proxy_name         = '' SELECT @proxy_name = NULL
    
   EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                  '@proxy_id',
                                                   @proxy_name OUTPUT,
                                                   @proxy_id   OUTPUT
    IF (@retval <> 0)
      RETURN(1) -- Failure

   EXECUTE @retval = sp_verify_subsystem_identifiers '@subsystem_name',
                                                  '@subsystem_id',
                                                   @subsystem_name OUTPUT,
                                                   @subsystem_id   OUTPUT
    IF (@retval <> 0)
      RETURN(1) -- Failure
   

  --TSQL subsystem is prohibited
  IF @subsystem_id = 1
   BEGIN
     RAISERROR(14530, -1, -1)
     RETURN(1) -- Failure
   END

  --check if we already added an user for the pair subsystem-proxy
  IF (EXISTS(SELECT * FROM sysproxysubsystem WHERE subsystem_id = @subsystem_id
               AND proxy_id = @proxy_id))
  BEGIN
     RAISERROR(14531, -1, -1)
     RETURN(1) -- Failure
   END
  
   INSERT INTO sysproxysubsystem
   (  subsystem_id,  proxy_id )
   VALUES
   (  @subsystem_id,    @proxy_id )

END
go

/**************************************************************/
/* sp_grant_login_to_proxy                           */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_grant_login_to_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_grant_login_to_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_grant_login_to_proxy
go
CREATE PROCEDURE dbo.sp_grant_login_to_proxy
   @login_name        NVARCHAR(256) = NULL,
   @fixed_server_role NVARCHAR(256) = NULL, 
   @msdb_role         NVARCHAR(256) = NULL, 
   -- must specify only one of above parameter to identify the type of login
   @proxy_id             int           = NULL,
   @proxy_name         sysname       = NULL
   -- must specify only one of above parameter to identify the proxy
AS
BEGIN
  DECLARE @retval   INT
  DECLARE @name nvarchar(256)
  DECLARE @flags INT
  DECLARE @sid VARBINARY(85)
  DECLARE @is_sysadmin BIT
  
  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))
  SELECT @fixed_server_role       = LTRIM(RTRIM(@fixed_server_role))
  SELECT @msdb_role               = LTRIM(RTRIM(@msdb_role))

  -- Turn [nullable] empty string parameters into NULLs
  IF @proxy_name         = '' SELECT @proxy_name = NULL
  IF @login_name         = '' SELECT @login_name = NULL
  IF @fixed_server_role  = '' SELECT @fixed_server_role = NULL
  IF @msdb_role          = '' SELECT @msdb_role  = NULL
    
  EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                 '@proxy_id',
                                                 @proxy_name OUTPUT,
                                                 @proxy_id   OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure

  EXECUTE @retval = sp_verify_login_identifiers  @login_name,
                                                 @fixed_server_role,
                                                 @msdb_role,
                                                 @name OUTPUT,
                                                 @sid OUTPUT,
                                                 @flags OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure
    
  -- is login member of sysadmin role?
  SELECT @is_sysadmin = 0
  IF (@login_name IS NOT NULL)
  BEGIN
     EXEC @is_sysadmin = sp_sqlagent_is_srvrolemember N'sysadmin', @login_name -- check role membership 
  END

  IF (@is_sysadmin = 1)
  BEGIN
   -- @name is sysadmin, it cannot granted to proxy
   -- issue a message and do nothing
   RAISERROR(14395, 10, 1, @name)
  END
  ELSE
  BEGIN
   --check if we already added an user for the pair subsystem-proxy
   IF (EXISTS(SELECT * FROM sysproxylogin WHERE proxy_id = @proxy_id 
               AND ISNULL(sid, 0) = ISNULL(@sid,0) 
               AND flags = @flags))
   BEGIN
      RAISERROR(14531, -1, -1)
      RETURN(1) -- Failure
   END

   INSERT INTO sysproxylogin
      (  proxy_id, sid,  flags )
      VALUES
      ( @proxy_id, @sid, @flags)
  END
END
go

/**************************************************************/
/* sp_revoke_login_from_proxy                                         */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_revoke_login_from_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_revoke_login_from_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_revoke_login_from_proxy
go

CREATE PROCEDURE dbo.sp_revoke_login_from_proxy
   @name         NVARCHAR(256),
   @proxy_id        INT = NULL,
   @proxy_name    sysname = NULL
   -- must specify only one of above parameter to identify the proxy
AS
BEGIN
   DECLARE @retval   INT
   DECLARE @sid VARBINARY(85)
   DECLARE @is_sysadmin BIT
   
   SET NOCOUNT ON

   -- Remove any leading/trailing spaces from parameters
   SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))
   SELECT @name                    = LTRIM(RTRIM(@name))

   -- Turn [nullable] empty string parameters into NULLs
   IF @proxy_name         = '' SELECT @proxy_name = NULL
   IF @name               = '' SELECT @name = NULL
    
   EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                  '@proxy_id',
                                                   @proxy_name OUTPUT,
                                                   @proxy_id   OUTPUT
   IF (@retval <> 0)
     RETURN(1) -- Failure
    
  -- is login member of sysadmin role?
  SELECT @is_sysadmin = 0
  IF (@name IS NOT NULL)
  BEGIN
    EXEC @is_sysadmin = sp_sqlagent_is_srvrolemember N'sysadmin', @name -- check role membership 
  END

  IF (@is_sysadmin = 1)
  BEGIN
    -- @name is sysadmin, it cannot be revoked from proxy
    -- issue a message and do nothing
    RAISERROR(14395, 10, -1, @name)
  END
  ELSE
  BEGIN  
    --force case insensitive comparation for NT users
    SELECT @sid = SUSER_SID(@name, 0)
    IF @sid IS NULL -- then @name is a MSDB role
       SELECT @sid = sid FROM sys.database_principals
       WHERE  name = @name

    --check parametrs validity
    IF (EXISTS(SELECT * FROM sysproxylogin WHERE
       proxy_id                  = @proxy_id AND
       ISNULL(sid, 0)            = ISNULL(@sid, 0)))
    BEGIN
       DELETE FROM sysproxylogin WHERE
       proxy_id     = @proxy_id AND 
       ISNULL(sid, 0)= ISNULL(@sid, 0) 
    END
    ELSE
    BEGIN
       RAISERROR(14523, -1, -1, @name, @proxy_name)
       RETURN(1) -- Failure       
    END   
  END

  RETURN(0)
END
go

/**************************************************************/
/* sp_revoke_proxy_from_subsystem                                       */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_revoke_proxy_from_subsystem...'
IF (NOT OBJECT_ID(N'dbo.sp_revoke_proxy_from_subsystem', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_revoke_proxy_from_subsystem
go

CREATE PROCEDURE dbo.sp_revoke_proxy_from_subsystem
   @proxy_id          INT = NULL,
   @proxy_name      sysname = NULL,
   -- must specify only one of above parameter to identify the proxyAS
   @subsystem_id    INT = NULL,
   @subsystem_name sysname = NULL
   -- must specify only one of above parameter to identify the subsystem
AS
BEGIN
   DECLARE @retval   INT
   DECLARE @proxy_account sysname
   SET NOCOUNT ON

   -- Remove any leading/trailing spaces from parameters
   SELECT @subsystem_name          = LTRIM(RTRIM(@subsystem_name))
   SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))

  -- Turn [nullable] empty string parameters into NULLs
  IF @subsystem_name    = '' SELECT @subsystem_name = NULL
  IF @proxy_name         = '' SELECT @proxy_name = NULL
    
   EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                                  '@proxy_id',
                                                   @proxy_name OUTPUT,
                                                   @proxy_id   OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure

   EXECUTE @retval = sp_verify_subsystem_identifiers '@subsystem_name',
                                                  '@subsystem_id',
                                                   @subsystem_name OUTPUT,
                                                   @subsystem_id   OUTPUT
  IF (@retval <> 0)
    RETURN(1) -- Failure
   
   
  --check parametrs validity
   IF (EXISTS(SELECT * FROM sysproxysubsystem WHERE
      subsystem_id = @subsystem_id AND 
      proxy_id     = @proxy_id ))
      BEGIN
        DELETE FROM sysproxysubsystem WHERE
           subsystem_id = @subsystem_id AND 
           proxy_id     = @proxy_id 
      END
   ELSE
      BEGIN
         RAISERROR(14600, -1, -1, @proxy_name, @subsystem_name)
         RETURN(1) -- Failure       
      END   

   RETURN(0)

END
go

/**************************************************************/
/* SP_ENUM_PROXY_FOR_SUBSYSTEM                                         */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_enum_proxy_for_subsystem...'
IF (NOT OBJECT_ID(N'dbo.sp_enum_proxy_for_subsystem', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_enum_proxy_for_subsystem
go

CREATE PROCEDURE sp_enum_proxy_for_subsystem
   @proxy_id      int = NULL,
   @proxy_name    sysname = NULL,
   -- must specify only one of above parameter to identify the proxy or none
   @subsystem_id  int = NULL,
   @subsystem_name sysname = NULL
   -- must specify only one of above parameter to identify the subsystem or none
AS
BEGIN
   DECLARE @retval   INT
   SET NOCOUNT ON

   -- Remove any leading/trailing spaces from parameters
   SELECT @subsystem_name          = LTRIM(RTRIM(@subsystem_name))
   SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))

  -- Turn [nullable] empty string parameters into NULLs
  IF @subsystem_name    = '' SELECT @subsystem_name = NULL
  IF @proxy_name         = '' SELECT @proxy_name = NULL

   IF @proxy_name IS NOT NULL OR @proxy_id IS NOT NULL
   BEGIN
      EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                          '@proxy_id',
                                          @proxy_name OUTPUT,
                                          @proxy_id   OUTPUT
      IF (@retval <> 0)
   RETURN(1) -- Failure
   END

   IF @subsystem_name IS NOT NULL OR @subsystem_id IS NOT NULL
   BEGIN
      EXECUTE @retval = sp_verify_subsystem_identifiers '@subsystem_name',
                                       '@subsystem_id',
                                       @subsystem_name OUTPUT,
                                       @subsystem_id   OUTPUT
      IF (@retval <> 0)
      RETURN(1) -- Failure
   END

  SELECT ps.subsystem_id AS subsystem_id, s.subsystem AS subsystem_name, ps.proxy_id AS proxy_id, p.name AS proxy_name
   FROM sysproxysubsystem ps JOIN sysproxies p ON ps.proxy_id = p.proxy_id
  JOIN syssubsystems s ON ps.subsystem_id = s.subsystem_id
   WHERE
        ISNULL(@subsystem_id, ps.subsystem_id) = ps.subsystem_id AND
        ISNULL(@proxy_id,     ps.proxy_id    ) = ps.proxy_id     
END
go

/**************************************************************/
/* sp_enum_login_for_proxy                                           */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_enum_login_for_proxy...'
IF (NOT OBJECT_ID(N'dbo.sp_enum_login_for_proxy', 'P') IS NULL)
  DROP PROCEDURE dbo.sp_enum_login_for_proxy
go

CREATE PROCEDURE sp_enum_login_for_proxy
   @name         NVARCHAR(256) = NULL,
   @proxy_id        INT           = NULL,
   @proxy_name    sysname       = NULL
   -- must specify only one of above parameter to identify the proxy or none
AS
BEGIN
   DECLARE @retval   INT
  DECLARE @sid VARBINARY(85)
   SET NOCOUNT ON

   -- Remove any leading/trailing spaces from parameters
   SELECT @proxy_name              = LTRIM(RTRIM(@proxy_name))
   SELECT @name                    = LTRIM(RTRIM(@name))

  -- Turn [nullable] empty string parameters into NULLs
  IF @proxy_name         = '' SELECT @proxy_name = NULL
  IF @name                 = '' SELECT @name = NULL

   IF @proxy_name IS NOT NULL OR @proxy_id IS NOT NULL
   BEGIN
      EXECUTE @retval = sp_verify_proxy_identifiers '@proxy_name',
                                          '@proxy_id',
                                          @proxy_name OUTPUT,
                                          @proxy_id   OUTPUT
     IF (@retval <> 0)
       RETURN(1) -- Failure
   END

   IF (@name IS NOT NULL) AND 
     --force case insensitive comparation for NT users
     (ISNULL(SUSER_SID(@name, 0), 0) = 0) AND
     (ISNULL(IS_SRVROLEMEMBER(@name), -1) = -1) AND
      (ISNULL(IS_MEMBER(@name), -1) = -1)
   BEGIN
            RAISERROR(14520, -1, -1, @name)
            RETURN(1) -- Failure    
   END      

  --force case insensitive comparation for NT users
  SELECT @sid = SUSER_SID(@name, 0)
  IF @sid IS NULL -- then @name is a MSDB role
    SELECT @sid = sid FROM sys.database_principals
    WHERE  name = @name

  SELECT pl.proxy_id AS proxy_id, p.name AS proxy_name, pl.flags as flags, 
  CASE pl.flags
          WHEN  0 THEN SUSER_SNAME(pl.sid)  -- SQLLOGIN, NT USER/GROUP          
          WHEN  1 THEN SUSER_SNAME(pl.sid)  -- SQL fixed server role 
          WHEN  2 THEN USER_NAME(msdb.dbo.get_principal_id(pl.sid)) -- MSDB role
          ELSE         NULL -- should never be the case
  END AS name,  pl.sid AS sid, msdb.dbo.get_principal_id(pl.sid) AS principal_id
   FROM sysproxylogin pl JOIN sysproxies p ON pl.proxy_id = p.proxy_id
   WHERE  
        COALESCE(@proxy_id,     pl.proxy_id,     0 ) = ISNULL(pl.proxy_id, 0)  AND
        COALESCE(@sid,          pl.sid,          0 ) = ISNULL(pl.sid, 0) 
END
go

/**************************************************************/
/* SP_SQLAGENT_GET_STARTUP_INFO                               */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sqlagent_get_startup_info...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_sqlagent_get_startup_info')
              AND (type = 'P')))
  DROP PROCEDURE sp_sqlagent_get_startup_info
go
CREATE PROCEDURE sp_sqlagent_get_startup_info
AS
BEGIN
  DECLARE @tbu INT
  DECLARE @agentAllowed INT

  SET NOCOUNT ON

  IF (ServerProperty('InstanceName') IS NULL)
  BEGIN
    EXECUTE @tbu = master.dbo.xp_qv '1338198028'
    EXECUTE @agentAllowed = master.dbo.xp_qv '2858542058'
  END
  ELSE
  BEGIN
    DECLARE @instancename NVARCHAR(128)
    SELECT @instancename = CONVERT(NVARCHAR(128), ServerProperty('InstanceName'))
    EXECUTE @tbu = master.dbo.xp_qv '1338198028', @instancename
    EXECUTE @agentAllowed = master.dbo.xp_qv '2858542058', @instancename
  END

  IF (@tbu < 0)
    SELECT @tbu = 0

  IF (@agentAllowed < 0)
    SELECT @agentAllowed = 0

  SELECT 'msdb_70_compatible' = (SELECT CASE WHEN cmptlevel >= 70 THEN 1 ELSE 0 END FROM master.dbo.sysdatabases WHERE (name = 'msdb')),
         'msdb_read_only' = DATABASEPROPERTY('msdb', 'IsReadOnly'),
         'msdb_available' = CASE ISNULL(DATABASEPROPERTY('msdb', 'IsSingleUser'), 0) WHEN 0 THEN 1 ELSE 0 END &
                            CASE ISNULL(DATABASEPROPERTY('msdb', 'IsDboOnly'), 0) WHEN 0 THEN 1 ELSE 0 END &
                            CASE ISNULL(DATABASEPROPERTY('msdb', 'IsNotRecovered'), 0) WHEN 0 THEN 1 ELSE 0 END &
                            CASE ISNULL(DATABASEPROPERTY('msdb', 'IsSuspect'), 0) WHEN 0 THEN 1 ELSE 0 END,
         'case_sensitive_server' = CASE ISNULL((SELECT 1 WHERE 'a' = 'A'), 0)
                                     WHEN 1 THEN 0
                                     ELSE 1
                                   END,
         'max_user_connection' = (SELECT value FROM master.dbo.syscurconfigs WHERE (config = 103)),
         'sql_server_name' = CONVERT(sysname, SERVERPROPERTY('SERVERNAME')),
         'tbu' = ISNULL(@tbu, 0),
         'platform' = PLATFORM(),
         'instance_name' = ISNULL(CONVERT(sysname, SERVERPROPERTY('INSTANCENAME')), 'MSSQLSERVER'),
         'is_clustered' = CONVERT(INT, SERVERPROPERTY('ISCLUSTERED')),
         'agent_allowed' = @agentAllowed

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_SQLAGENT_HAS_SERVER_ACCESS                              */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sqlagent_has_server_access...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_sqlagent_has_server_access')
              AND (type = 'P')))
  DROP PROCEDURE sp_sqlagent_has_server_access
go
CREATE PROCEDURE sp_sqlagent_has_server_access
  @login_name         sysname = NULL,
  @is_sysadmin_member INT     = NULL OUTPUT
AS
BEGIN
  DECLARE @has_server_access BIT
  DECLARE @is_sysadmin       BIT
  DECLARE @actual_login_name sysname
  DECLARE @cachedate         DATETIME

  SET NOCOUNT ON

  SELECT @cachedate = NULL

  -- remove expired entries from the cache
  DELETE msdb.dbo.syscachedcredentials
  WHERE  DATEDIFF(MINUTE, cachedate, GETDATE()) >= 29

  -- query the cache
  SELECT  @is_sysadmin = is_sysadmin_member,
          @has_server_access = has_server_access,
          @cachedate = cachedate
  FROM    msdb.dbo.syscachedcredentials
  WHERE   login_name = @login_name
  AND     DATEDIFF(MINUTE, cachedate, GETDATE()) < 29

  IF (@cachedate IS NOT NULL)
  BEGIN
    -- no output variable
    IF (@is_sysadmin_member IS NULL)
    BEGIN
      -- Return result row
      SELECT has_server_access = @has_server_access,
             is_sysadmin       = @is_sysadmin,
             actual_login_name = @login_name
      RETURN
    END
    ELSE
    BEGIN
      SELECT @is_sysadmin_member = @is_sysadmin
      RETURN
    END
  END -- select from cache

  -- Set defaults
  SELECT @has_server_access = 0
  SELECT @is_sysadmin = 0
  SELECT @actual_login_name = FORMATMESSAGE(14205)

  IF (@login_name IS NULL)
  BEGIN
    SELECT has_server_access = 1,
           is_sysadmin       = IS_SRVROLEMEMBER(N'sysadmin'),
           actual_login_name = SUSER_SNAME()
    RETURN
  END

  IF (@login_name LIKE '%\%')
  BEGIN
    -- Handle the LocalSystem account ('NT AUTHORITY\SYSTEM') as a special case
    IF (UPPER(@login_name collate SQL_Latin1_General_CP1_CS_AS) = N'NT AUTHORITY\SYSTEM')
    BEGIN
      IF (EXISTS (SELECT *
                  FROM master.dbo.syslogins
                  WHERE (UPPER(loginname collate SQL_Latin1_General_CP1_CS_AS) = N'NT AUTHORITY\SYSTEM')))
      BEGIN
        SELECT @has_server_access = hasaccess,
               @is_sysadmin = sysadmin,
               @actual_login_name = loginname
        FROM master.dbo.syslogins
        WHERE (UPPER(loginname collate SQL_Latin1_General_CP1_CS_AS) = N'NT AUTHORITY\SYSTEM')
      END
      ELSE
      IF (EXISTS (SELECT *
                  FROM master.dbo.syslogins
                  WHERE (UPPER(loginname collate SQL_Latin1_General_CP1_CS_AS) = N'BUILTIN\ADMINISTRATORS')))
      BEGIN
        SELECT @has_server_access = hasaccess,
               @is_sysadmin = sysadmin,
               @actual_login_name = loginname
        FROM master.dbo.syslogins
        WHERE (UPPER(loginname collate SQL_Latin1_General_CP1_CS_AS) = N'BUILTIN\ADMINISTRATORS')
      END
    END
    ELSE
    BEGIN
      -- Check if the NT login has been explicitly denied access
      IF (EXISTS (SELECT *
                  FROM master.dbo.syslogins
                  WHERE (loginname = @login_name)
                    AND (denylogin = 1)))
      BEGIN
        SELECT @has_server_access = 0,
               @is_sysadmin = sysadmin,
               @actual_login_name = loginname
        FROM master.dbo.syslogins
        WHERE (loginname = @login_name)
      END
      ELSE
      BEGIN
        -- declare table variable for storing results
        DECLARE @xp_results TABLE
        (
        account_name      sysname      COLLATE database_default NOT NULL PRIMARY KEY,
        type              NVARCHAR(10) COLLATE database_default NOT NULL,
        privilege         NVARCHAR(10) COLLATE database_default NOT NULL,
        mapped_login_name sysname      COLLATE database_default NOT NULL,
        permission_path   sysname      COLLATE database_default NULL
        )

        -- Call xp_logininfo to determine server access
        INSERT INTO @xp_results
        EXECUTE master.dbo.xp_logininfo @login_name

        SELECT @has_server_access = CASE COUNT(*)
                                      WHEN 0 THEN 0
                                      ELSE 1
                                    END
        FROM @xp_results
        SELECT @actual_login_name = mapped_login_name,
               @is_sysadmin = CASE UPPER(privilege collate SQL_Latin1_General_CP1_CS_AS)
                                WHEN 'ADMIN' THEN 1
                                ELSE 0
                             END
        FROM @xp_results
      END
    END
  END
  ELSE
  BEGIN
    -- Standard login
    IF (EXISTS (SELECT *
                FROM master.dbo.syslogins
                WHERE (loginname = @login_name)))
    BEGIN
      SELECT @has_server_access = hasaccess,
             @is_sysadmin = sysadmin,
             @actual_login_name = loginname
      FROM master.dbo.syslogins
      WHERE (loginname = @login_name)
    END
  END

  -- update the cache only if something is found
  IF  (UPPER(@actual_login_name collate SQL_Latin1_General_CP1_CS_AS) <> '(UNKNOWN)')
  BEGIN
    -- Procedure starts its own transaction.
    BEGIN TRANSACTION;
    
    -- Modify database.
    -- use a try catch login to prevent any error when trying 
    -- to insert/update syscachedcredentials table
    -- no need to fail since the job owner has been validated
    BEGIN TRY      
      IF EXISTS (SELECT * FROM msdb.dbo.syscachedcredentials WITH (TABLOCKX) WHERE login_name = @login_name)
      BEGIN
        UPDATE msdb.dbo.syscachedcredentials
        SET    has_server_access = @has_server_access,
              is_sysadmin_member = @is_sysadmin,
              cachedate = GETDATE()
        WHERE  login_name = @login_name
      END
      ELSE
      BEGIN
        INSERT INTO msdb.dbo.syscachedcredentials(login_name, has_server_access, is_sysadmin_member) 
        VALUES(@login_name, @has_server_access, @is_sysadmin)
      END
      END TRY
      BEGIN CATCH
          -- If an error occurred we want to ignore it
      END CATCH
      
      -- The procedure must commit the transaction it started.
      COMMIT TRANSACTION;  
  END
  
  IF (@is_sysadmin_member IS NULL)
    -- Return result row
    SELECT has_server_access = @has_server_access,
           is_sysadmin       = @is_sysadmin,
           actual_login_name = @actual_login_name
  ELSE
    -- output variable only
    SELECT @is_sysadmin_member = @is_sysadmin
END
go


/**************************************************************/
/* SP_SEM_ADD_MESSAGE [used by SEM only]                      */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sem_add_message...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_sem_add_message')
              AND (type = 'P')))
  DROP PROCEDURE sp_sem_add_message
go
CREATE PROCEDURE sp_sem_add_message
  @msgnum   INT           = NULL,
  @severity SMALLINT      = NULL,
  @msgtext  NVARCHAR(255) = NULL,
  @lang     sysname       = NULL, -- Message language name
  @with_log VARCHAR(5)    = 'FALSE',
  @replace  VARCHAR(7)    = NULL
AS
BEGIN
  DECLARE @retval        INT
  DECLARE @language_name sysname

  SET NOCOUNT ON

  SET ROWCOUNT 1
  SELECT @language_name = name
  FROM sys.syslanguages
  WHERE msglangid = (SELECT number
                     FROM master.dbo.spt_values
                     WHERE (type = 'LNG')
                       AND (name = @lang))
  SET ROWCOUNT 0

  SELECT @language_name = ISNULL(@language_name, 'us_english')
  EXECUTE @retval = master.dbo.sp_addmessage @msgnum, @severity, @msgtext, @language_name, @with_log, @replace
  RETURN(@retval)
END
go

/**************************************************************/
/* SP_SEM_DROP_MESSAGE [used by SEM only]                     */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sem_drop_message...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_sem_drop_message')
              AND (type = 'P')))
  DROP PROCEDURE sp_sem_drop_message
go
CREATE PROCEDURE sp_sem_drop_message
  @msgnum int     = NULL,
  @lang   sysname = NULL -- Message language name
AS
BEGIN
  DECLARE @retval        INT
  DECLARE @language_name sysname

  SET NOCOUNT ON

  SET ROWCOUNT 1
  SELECT @language_name = name
  FROM sys.syslanguages
  WHERE msglangid = (SELECT number
                     FROM master.dbo.spt_values
                     WHERE (type = 'LNG')
                       AND (name = @lang))
  SET ROWCOUNT 0

  SELECT @language_name = ISNULL(@language_name, 'us_english')
  EXECUTE @retval = master.dbo.sp_dropmessage @msgnum, @language_name
  RETURN(@retval)
END
go

/**************************************************************/
/* SP_GET_MESSAGE_DESCRIPTION [used by SEM only]              */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_get_message_description...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_get_message_description')
              AND (type = 'P')))
  DROP PROCEDURE sp_get_message_description
go
CREATE PROCEDURE sp_get_message_description
  @error INT
AS
BEGIN
  IF EXISTS (SELECT * FROM master.dbo.sysmessages WHERE (error = @error) AND (msglangid = (SELECT msglangid FROM sys.syslanguages WHERE (langid = @@langid))))
    SELECT description FROM master.dbo.sysmessages WHERE (error = @error) AND (msglangid = (SELECT msglangid FROM sys.syslanguages WHERE (langid = @@langid)))
  ELSE
    SELECT description FROM master.dbo.sysmessages WHERE (error = @error) AND (msglangid = 1033)
END
go

/**************************************************************/
/* SP_SQLAGENT_GET_PERF_COUNTERS                              */
/**************************************************************/
PRINT ''
PRINT 'Creating procedure sp_sqlagent_get_perf_counters...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_sqlagent_get_perf_counters')
              AND (type = 'P')))
  DROP PROCEDURE sp_sqlagent_get_perf_counters
go
CREATE PROCEDURE sp_sqlagent_get_perf_counters
  @all_counters BIT = 0
AS
BEGIN

  SET NOCOUNT ON

  -- 32 bit fraction counter types
  DECLARE @perfTypeRawFraction INT
  DECLARE @perfTypeRawBase     INT

  -- A counter of type PERF_RAW_FRACTION, which is a 32-bit counter value.
  SET @perfTypeRawFraction = 537003008 --  In hex, 0x20020400.

   -- A count of type PERF_RAW_BASE, which is the 32-bit divisor used
   -- when handling PERF_RAW_FRACTION types. This counter type should
   -- not be displayed to the user since it is used for mathematical
   -- operations.
  SET @perfTypeRawBase     = 1073939459 -- In hex, 0x40030403.


  -- 64 bit fraction counter types
  DECLARE @perfTypeLargeRawFraction INT
  DECLARE @perfTypeLargeRawBase     INT

  -- A counter of type PERF_LARGE RAW_FRACTION, which is a 64-bit counter value.
  SET @perfTypeLargeRawFraction = 537003264 --  In hex, 0x20020500.

   -- A count of type PERF_LARGE_RAW_BASE, which is the 64-bit divisor used
   -- when handling PERF_LARGE_RAW_FRACTION types. This counter type should
   -- not be displayed to the user since it is used for mathematical
   -- operations.
  SET @perfTypeLargeRawBase     = 1073939712 -- In hex, 0x40030500.



  IF (@all_counters = 0)
  BEGIN

      SELECT 'object_name' = RTRIM(SUBSTRING(spi1.object_name, 1, 50)),
             'counter_name' = RTRIM(SUBSTRING(spi1.counter_name, 1, 50)),
             'instance_name' = CASE spi1.instance_name
                             WHEN N'' THEN NULL
                             ELSE RTRIM(spi1.instance_name)
                           END,
         'value' = CASE spi1.cntr_type
                     WHEN @perfTypeRawFraction -- 32 bit fraction
                       THEN CONVERT(FLOAT, spi1.cntr_value) / (SELECT CASE spi2.cntr_value WHEN 0 THEN 1 ELSE spi2.cntr_value END
                                                               FROM sys.dm_os_performance_counters spi2
                                                               WHERE (spi1.counter_name + ' ' = SUBSTRING(spi2.counter_name, 1, PATINDEX('% Base%', spi2.counter_name)))
                                                                 AND (spi1.instance_name = spi2.instance_name)
                                                                 AND (spi2.cntr_type = @perfTypeRawBase))
                     WHEN @perfTypeLargeRawFraction  -- 64 bit fraction
                       THEN CONVERT(FLOAT, spi1.cntr_value) / (SELECT CASE spi2.cntr_value WHEN 0 THEN 1 ELSE spi2.cntr_value END
                                                               FROM sys.dm_os_performance_counters spi2
                                                               WHERE (spi1.counter_name + ' ' = SUBSTRING(spi2.counter_name, 1, PATINDEX('% Base%', spi2.counter_name)))
                                                                 AND (spi1.instance_name = spi2.instance_name)
                                                                 AND (spi2.cntr_type = @perfTypeLargeRawBase))
                     ELSE spi1.cntr_value
                   END,
       'type' = spi1.cntr_type
        
        FROM sys.dm_os_performance_counters spi1,
        (
                SELECT DISTINCT SUBSTRING(performance_condition, 1, CHARINDEX('|', performance_condition, PATINDEX('%_|_%', performance_condition) + 2) - 1)
                 as performance_condition_s  FROM msdb.dbo.sysalerts
                WHERE (performance_condition IS NOT NULL)
                AND ISNULL(event_id, 0) <> 8 -- exclude WMI events that reuse performance_condition field
                AND (enabled = 1)
        ) tmp -- We want to select only those counters that have an enabled performance sysalert
        WHERE (spi1.cntr_type <> @perfTypeRawBase)      -- ignore 32-bit denominator counter type
          AND (spi1.cntr_type <> @perfTypeLargeRawBase) -- ignore 64-bit denominator counter type
          AND (tmp.performance_condition_s = RTRIM(spi1.object_name) + '|' + RTRIM(spi1.counter_name))

  END
  ELSE
  BEGIN

    SELECT 'object_name' = RTRIM(SUBSTRING(spi1.object_name, 1, 50)),
           'counter_name' = RTRIM(SUBSTRING(spi1.counter_name, 1, 50)),
           'instance_name' = CASE spi1.instance_name
                             WHEN N'' THEN NULL
                             ELSE RTRIM(spi1.instance_name)
                           END,
         'value' = CASE spi1.cntr_type
                     WHEN @perfTypeRawFraction -- 32 bit fraction
                       THEN CONVERT(FLOAT, spi1.cntr_value) / (SELECT CASE spi2.cntr_value WHEN 0 THEN 1 ELSE spi2.cntr_value END
                                                               FROM sys.dm_os_performance_counters spi2
                                                               WHERE (spi1.counter_name + ' ' = SUBSTRING(spi2.counter_name, 1, PATINDEX('% Base%', spi2.counter_name)))
                                                                 AND (spi1.instance_name = spi2.instance_name)
                                                                 AND (spi2.cntr_type = @perfTypeRawBase))
                     WHEN @perfTypeLargeRawFraction  -- 64 bit fraction
                       THEN CONVERT(FLOAT, spi1.cntr_value) / (SELECT CASE spi2.cntr_value WHEN 0 THEN 1 ELSE spi2.cntr_value END
                                                               FROM sys.dm_os_performance_counters spi2
                                                               WHERE (spi1.counter_name + ' ' = SUBSTRING(spi2.counter_name, 1, PATINDEX('% Base%', spi2.counter_name)))
                                                                 AND (spi1.instance_name = spi2.instance_name)
                                                                 AND (spi2.cntr_type = @perfTypeLargeRawBase))
                     ELSE spi1.cntr_value
                   END,
       'type' = spi1.cntr_type
    FROM sys.dm_os_performance_counters spi1
    WHERE (spi1.cntr_type <> @perfTypeRawBase)      -- ignore 32-bit denominator counter type
      AND (spi1.cntr_type <> @perfTypeLargeRawBase) -- ignore 64-bit denominator counter type
  END

END

GO


/**************************************************************/
/* SP_SQLAGENT_NOTIFY                                         */
/*                                                            */
/* NOTE: We define this procedure here instead of in the      */
/*      'Support procedures' section because of the many      */
/*       other procedures that reference it.                  */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_sqlagent_notify...'
go

IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_sqlagent_notify')
              AND (type = 'P')))
  DROP PROCEDURE sp_sqlagent_notify
go
CREATE PROCEDURE sp_sqlagent_notify
  @op_type     NCHAR(1),                -- One of: J (Job action [refresh or start/stop]),
                                        --         S (Schedule action [refresh only])
                                        --         A (Alert action [refresh only]),
                                        --         G (Re-cache all registry settings),
                                        --         D (Dump job [or job schedule] cache to errorlog)
                                        --         P (Force an immediate poll of the MSX)
                                        --         L (Cycle log file)
                                        --         T (Test WMI parameters (namespace and query))
  @job_id      UNIQUEIDENTIFIER = NULL, -- JobID (for OpTypes 'J', 'S' and 'D')
  @schedule_id INT              = NULL, -- ScheduleID (for OpType 'S')
  @alert_id    INT              = NULL, -- AlertID (for OpType 'A')
  @action_type NCHAR(1)         = NULL, -- For 'J' one of: R (Run - no service check),
                                        --                 S (Start - with service check),
                                        --                 I (Insert),
                                        --                 U (Update),
                                        --                 D (Delete),
                                        --                 C (Stop [Cancel])
                                        -- For 'S' or 'A' one of: I (Insert),
                                        --                        U (Update),
                                        --                        D (Delete)
  @error_flag  INT              = 1,    -- Set to 0 to suppress the error from xp_sqlagent_notify if SQLServer agent is not running
  @wmi_namespace nvarchar(128) = NULL,
  @wmi_query     nvarchar(512) = NULL
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @id_as_char     VARCHAR(10)
  DECLARE @job_id_as_char VARCHAR(36)
  DECLARE @nt_user_name   NVARCHAR(100)

  SET NOCOUNT ON

  SELECT @retval = 0 -- Success

  -- Make sure that we're dealing only with uppercase characters
  SELECT @op_type     = UPPER(@op_type collate SQL_Latin1_General_CP1_CS_AS)
  SELECT @action_type = UPPER(@action_type collate SQL_Latin1_General_CP1_CS_AS)

  -- Verify operation code
  IF (CHARINDEX(@op_type, N'JSAGDPLT') = 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@op_type', 'J, S, A, G, D, P, L, T')
    RETURN(1) -- Failure
  END

  -- Check the job id for those who use it
  IF (CHARINDEX(@op_type, N'JSD') <> 0)
  BEGIN
    IF (NOT ((@op_type = N'D' OR @op_type = N'S') AND (@job_id IS NULL))) -- For 'D' and 'S' job_id is optional
    BEGIN
      IF ((@job_id IS NULL) OR
          ((@action_type <> N'D') AND NOT EXISTS (SELECT *
                                                  FROM msdb.dbo.sysjobs_view
                                                  WHERE (job_id = @job_id))))
      BEGIN
        SELECT @job_id_as_char = CONVERT(VARCHAR(36), @job_id)
        RAISERROR(14262, -1, -1, '@job_id', @job_id_as_char)
        RETURN(1) -- Failure
      END
    END
  END

  -- Verify 'job' action parameters
  IF (@op_type = N'J')
  BEGIN
    SELECT @alert_id = 0
    IF (@schedule_id IS NULL) SELECT @schedule_id = 0

    -- The schedule_id (if specified) is the start step
    IF ((CHARINDEX(@action_type, N'RS') <> 0) AND (@schedule_id <> 0))
    BEGIN
      IF (NOT EXISTS (SELECT *
                      FROM msdb.dbo.sysjobsteps
                      WHERE (job_id = @job_id)
                        AND (step_id = @schedule_id)))
      BEGIN
        SELECT @id_as_char = ISNULL(CONVERT(VARCHAR, @schedule_id), '(null)')
        RAISERROR(14262, -1, -1, '@schedule_id', @id_as_char)
        RETURN(1) -- Failure
      END
    END
    ELSE
      SELECT @schedule_id = 0

    IF (CHARINDEX(@action_type, N'RSIUDC') = 0)
    BEGIN
      RAISERROR(14266, -1, -1, '@action_type', 'R, S, I, U, D, C')
      RETURN(1) -- Failure
    END
  END

  -- Verify 'schedule' action parameters
  IF (@op_type = N'S')
  BEGIN
    SELECT @alert_id = 0

    IF (CHARINDEX(@action_type, N'IUD') = 0)
    BEGIN
      RAISERROR(14266, -1, -1, '@action_type', 'I, U, D')
      RETURN(1) -- Failure
    END

    IF ((@schedule_id IS NULL) OR
        ((@action_type <> N'D') AND NOT EXISTS (SELECT *
                                                FROM msdb.dbo.sysschedules
                                                WHERE (schedule_id = @schedule_id))))
    BEGIN
      SELECT @id_as_char = ISNULL(CONVERT(VARCHAR, @schedule_id), '(null)')
      RAISERROR(14262, -1, -1, '@schedule_id', @id_as_char)
      RETURN(1) -- Failure
    END
  END

  -- Verify 'alert' action parameters
  IF (@op_type = N'A')
  BEGIN
    SELECT @job_id = 0x00
    SELECT @schedule_id = 0

    IF (CHARINDEX(@action_type, N'IUD') = 0)
    BEGIN
      RAISERROR(14266, -1, -1, '@action_type', 'I, U, D')
      RETURN(1) -- Failure
    END

    IF ((@alert_id IS NULL) OR
        ((@action_type <> N'D') AND NOT EXISTS (SELECT *
                                                FROM msdb.dbo.sysalerts
                                                WHERE (id = @alert_id))))
    BEGIN
      SELECT @id_as_char = ISNULL(CONVERT(VARCHAR, @alert_id), '(null)')
      RAISERROR(14262, -1, -1, '@alert_id', @id_as_char)
      RETURN(1) -- Failure
    END
  END

  -- Verify 'registry', 'job dump' and 'force MSX poll' and 'cycle log' action parameters
  IF (CHARINDEX(@op_type, N'GDPL') <> 0)
  BEGIN
    IF (@op_type <> N'D')
      SELECT @job_id = 0x00
    SELECT @alert_id = 0
    SELECT @schedule_id = 0
    SELECT @action_type = NULL
  END

  -- Parameters are valid, so now check execution permissions...

  -- For anything except a job (or schedule) action the caller must be SysAdmin, DBO, or DB_Owner
  IF (@op_type NOT IN (N'J', N'S'))
  BEGIN
    IF NOT ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR
            (ISNULL(IS_MEMBER(N'db_owner'), 0) = 1) OR
            (UPPER(USER_NAME() collate SQL_Latin1_General_CP1_CS_AS) = N'DBO'))
    BEGIN
      RAISERROR(14260, -1, -1)
      RETURN(1) -- Failure
    END
  END

  -- For a Job Action the caller must be SysAdmin, DBO, DB_Owner, or the job owner
  IF (@op_type = N'J')
  BEGIN
    IF NOT ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR
            (ISNULL(IS_MEMBER(N'db_owner'), 0) = 1) OR
            (UPPER(USER_NAME() collate SQL_Latin1_General_CP1_CS_AS) = N'DBO') OR
            (EXISTS (SELECT *
                     FROM msdb.dbo.sysjobs_view
                     WHERE (job_id = @job_id))))
    BEGIN
      RAISERROR(14252, -1, -1)
      RETURN(1) -- Failure
    END
  END

  --verify WMI parameters
  IF (@op_type = N'T')
  BEGIN
   SELECT @wmi_namespace = LTRIM(RTRIM(@wmi_namespace))
   SELECT @wmi_query = LTRIM(RTRIM(@wmi_query))  
    IF (@wmi_namespace IS NULL) or (@wmi_query IS NULL)
   BEGIN
          RAISERROR(14508, 16, 1)
          RETURN(1) -- Failure      
   END
  END

  -- Ok, let's do it...
  SELECT @nt_user_name = ISNULL(NT_CLIENT(), ISNULL(SUSER_SNAME(), FORMATMESSAGE(14205)))
  EXECUTE @retval = master.dbo.xp_sqlagent_notify @op_type, @job_id, @schedule_id, @alert_id, @action_type, @nt_user_name, @error_flag, @@trancount, @wmi_namespace, @wmi_query

  RETURN(@retval)
END
go

/**************************************************************/
/* SP_IS_SQLAGENT_STARTING                                    */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_is_sqlagent_starting...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_is_sqlagent_starting')
              AND (type = 'P')))
  DROP PROCEDURE sp_is_sqlagent_starting
go
CREATE PROCEDURE sp_is_sqlagent_starting
AS
BEGIN
  DECLARE @retval INT

  SELECT @retval = 0
  EXECUTE master.dbo.xp_sqlagent_is_starting @retval OUTPUT
  IF (@retval = 1)
    RAISERROR(14258, -1, -1)

  RETURN(@retval)
END
go


/**************************************************************/
/* SP_VERIFY_JOB_IDENTIFIERS                                  */
/*                                                            */
/* NOTE: We define this procedure here instead of in the      */
/*      'Support procedures' section because of the many      */
/*       other procedures that reference it.                  */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_job_identifiers...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_job_identifiers')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_job_identifiers
go
CREATE PROCEDURE sp_verify_job_identifiers
  @name_of_name_parameter  VARCHAR(60),             -- Eg. '@job_name'
  @name_of_id_parameter    VARCHAR(60),             -- Eg. '@job_id'
  @job_name                sysname          OUTPUT, -- Eg. 'My Job'
  @job_id                  UNIQUEIDENTIFIER OUTPUT,
  @sqlagent_starting_test  VARCHAR(7) = 'TEST',      -- By default we DO want to test if SQLServerAgent is running (caller should specify 'NO_TEST' if not desired)
  @owner_sid                VARBINARY(85) = NULL OUTPUT  
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @job_id_as_char VARCHAR(36)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @job_name               = LTRIM(RTRIM(@job_name))

  IF (@job_name = N'') SELECT @job_name = NULL

  IF ((@job_name IS NULL)     AND (@job_id IS NULL)) OR
     ((@job_name IS NOT NULL) AND (@job_id IS NOT NULL))
  BEGIN
    RAISERROR(14294, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check job id
  IF (@job_id IS NOT NULL)
  BEGIN
    SELECT @job_name = name,
           @owner_sid = owner_sid
    FROM msdb.dbo.sysjobs_view
    WHERE (job_id = @job_id)
    
    -- the view would take care of all the permissions issues.
    IF (@job_name IS NULL) 
    BEGIN
      SELECT @job_id_as_char = CONVERT(VARCHAR(36), @job_id)
      RAISERROR(14262, -1, -1, '@job_id', @job_id_as_char)
      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check job name
  IF (@job_name IS NOT NULL)
  BEGIN
    -- Check if the job name is ambiguous
    IF ((SELECT COUNT(*)
         FROM msdb.dbo.sysjobs_view
         WHERE (name = @job_name)) > 1)
    BEGIN
      RAISERROR(14293, -1, -1, @job_name, @name_of_id_parameter, @name_of_name_parameter)
      RETURN(1) -- Failure
    END

    -- The name is not ambiguous, so get the corresponding job_id (if the job exists)
    SELECT @job_id = job_id,
           @owner_sid = owner_sid
    FROM msdb.dbo.sysjobs_view
    WHERE (name = @job_name)
    
    -- the view would take care of all the permissions issues.
    IF (@job_id IS NULL) 
    BEGIN
      RAISERROR(14262, -1, -1, '@job_name', @job_name)
      RETURN(1) -- Failure
    END
  END

  IF (@sqlagent_starting_test = 'TEST')
  BEGIN
    -- Finally, check if SQLServerAgent is in the process of starting and if so prevent the
    -- calling SP from running
    EXECUTE @retval = msdb.dbo.sp_is_sqlagent_starting
    IF (@retval <> 0)
      RETURN(1) -- Failure
  END

  RETURN(0) -- Success
END
go


/**************************************************************/
/* SP_VERIFY_SCHEDULE_IDENTIFIERS                             */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_schedule_identifiers...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_schedule_identifiers')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_schedule_identifiers
go
CREATE PROCEDURE sp_verify_schedule_identifiers
  @name_of_name_parameter   VARCHAR(60),             -- Eg. '@schedule_name'
  @name_of_id_parameter     VARCHAR(60),             -- Eg. '@schedule_id'
  @schedule_name            sysname             OUTPUT, 
  @schedule_id              INT                 OUTPUT,
  @owner_sid                VARBINARY(85)       OUTPUT,
  @orig_server_id           INT                 OUTPUT,
  @job_id_filter            UNIQUEIDENTIFIER    = NULL
AS
BEGIN
  DECLARE @retval         INT
  DECLARE @schedule_id_as_char VARCHAR(36)
  DECLARE @sch_name_count INT

  SET NOCOUNT ON
  
  -- Remove any leading/trailing spaces from parameters
  SELECT @name_of_name_parameter = LTRIM(RTRIM(@name_of_name_parameter))
  SELECT @name_of_id_parameter   = LTRIM(RTRIM(@name_of_id_parameter))
  SELECT @schedule_name          = LTRIM(RTRIM(@schedule_name))
  SELECT @sch_name_count         = 0
  

  IF (@schedule_name = N'') SELECT @schedule_name = NULL

  IF ((@schedule_name IS NULL)     AND (@schedule_id IS NULL)) OR
     ((@schedule_name IS NOT NULL) AND (@schedule_id IS NOT NULL))
  BEGIN
    RAISERROR(14373, -1, -1, @name_of_id_parameter, @name_of_name_parameter)
    RETURN(1) -- Failure
  END

  -- Check schedule id
  IF (@schedule_id IS NOT NULL)
  BEGIN
    -- if Agent is calling look in all schedules not just the local server schedules
    if(PROGRAM_NAME() LIKE N'SQLAgent%')
    BEGIN
        -- Look at all schedules
        SELECT @schedule_name   = name,
           @owner_sid           = owner_sid,
           @orig_server_id      = originating_server_id
        FROM msdb.dbo.sysschedules
        WHERE (schedule_id = @schedule_id)
    END
    ELSE
    BEGIN
        --Look at local schedules only
        SELECT @schedule_name   = name,
           @owner_sid           = owner_sid,
           @orig_server_id      = originating_server_id
        FROM msdb.dbo.sysschedules_localserver_view
        WHERE (schedule_id = @schedule_id)
    END

    IF (@schedule_name IS NULL)
    BEGIN
     --If the schedule is from an MSX and a sysadmin is calling report a specific 'MSX' message
      IF(PROGRAM_NAME() NOT LIKE N'SQLAgent%' AND
         ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 AND
         EXISTS(SELECT * 
                FROM msdb.dbo.sysschedules as sched
                  JOIN msdb.dbo.sysoriginatingservers_view as svr
                    ON sched.originating_server_id = svr.originating_server_id
                WHERE (schedule_id = @schedule_id) AND 
                      (svr.master_server = 1)))
     BEGIN
       RAISERROR(14274, -1, -1)
     END
      ELSE  
      BEGIN
        SELECT @schedule_id_as_char = CONVERT(VARCHAR(36), @schedule_id)
        RAISERROR(14262, -1, -1, '@schedule_id', @schedule_id_as_char)
      END

      RETURN(1) -- Failure
    END
  END
  ELSE
  -- Check job name
  IF (@schedule_name IS NOT NULL)
  BEGIN
    -- if a job_id is supplied use it as a filter. This helps with V8 legacy support
    IF(@job_id_filter IS NOT NULL)
    BEGIN
        -- Check if the job name is ambiguous and also get the schedule_id optimistically.
        -- If the name is not ambiguous this gets the corresponding schedule_id (if the schedule exists)
        SELECT @sch_name_count = COUNT(*),
               @schedule_id    = MIN(s.schedule_id),
               @owner_sid      = MIN(owner_sid),
               @orig_server_id = MIN(originating_server_id)
        FROM msdb.dbo.sysschedules_localserver_view as s
          JOIN msdb.dbo.sysjobschedules as js 
            ON s.schedule_id = js.schedule_id
        WHERE (name = @schedule_name) AND
              (js.job_id = @job_id_filter)
    END
    ELSE
    BEGIN
      -- Check if the job name is ambiguous from the count(*) result
        -- If the name is not ambiguous it is safe use the fields returned by the MIN() function
        SELECT @sch_name_count = COUNT(*),
         @schedule_id     = MIN(schedule_id),
            @owner_sid       = MIN(owner_sid),
            @orig_server_id  = MIN(originating_server_id)
        FROM msdb.dbo.sysschedules_localserver_view
        WHERE (name = @schedule_name)
    END

    IF(@sch_name_count > 1)
    BEGIN
        -- ambiguous, user needs to use a schedule_id instead of a schedule_name
        RAISERROR(14371, -1, -1, @schedule_name, @name_of_id_parameter, @name_of_name_parameter)
        RETURN(1) -- Failure
    END

    --schedule_id isn't visible to this user or doesn't exist
    IF (@schedule_id IS NULL)
    BEGIN
      --If the schedule is from an MSX and a sysadmin is calling report a specific 'MSX' message
      IF(PROGRAM_NAME() NOT LIKE N'SQLAgent%' AND
         ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 AND
         EXISTS(SELECT * 
                FROM msdb.dbo.sysschedules as sched
                  JOIN msdb.dbo.sysoriginatingservers_view as svr
                    ON sched.originating_server_id = svr.originating_server_id
                  JOIN msdb.dbo.sysjobschedules as js 
                    ON sched.schedule_id = js.schedule_id
                WHERE (svr.master_server = 1) AND
                      (name = @schedule_name) AND
                      ((@job_id_filter IS NULL) OR (js.job_id = @job_id_filter))))
     BEGIN
       RAISERROR(14274, -1, -1)
     END
      ELSE
      BEGIN
        --If not a MSX schedule raise local error
        RAISERROR(14262, -1, -1, '@schedule_name', @schedule_name)
      END

      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_VERIFY_JOBPROC_CALLER                                   */
/*                                                            */
/* NOTE: We define this procedure here instead of in the      */
/*      'Support procedures' section because of the many      */
/*       other procedures that reference it.                  */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_jobproc_caller...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_jobproc_caller')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_jobproc_caller
go
CREATE PROCEDURE sp_verify_jobproc_caller
  @job_id       UNIQUEIDENTIFIER,
  @program_name sysname
AS
BEGIN
  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @program_name = LTRIM(RTRIM(@program_name))

  IF (EXISTS (SELECT    *
              FROM      msdb.dbo.sysjobs_view
              WHERE     (job_id = @job_id)
              AND       (master_server = 1) )) -- master_server = 1 filters on MSX jobs in this TSX server
              AND       (PROGRAM_NAME() NOT LIKE @program_name)
  BEGIN
    RAISERROR(14274, -1, -1)
    RETURN(1) -- Failure
  END

  RETURN(0)
END
go

/**************************************************************/
/* SP_DOWNLOADED_ROW_LIMITER                                  */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_downloaded_row_limiter...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_downloaded_row_limiter')
              AND (type = 'P')))
  DROP PROCEDURE dbo.sp_downloaded_row_limiter
go
CREATE PROCEDURE sp_downloaded_row_limiter
  @server_name sysname -- Target server name
AS
BEGIN
  -- This trigger controls how many downloaded (status = 1) sysdownloadlist rows exist
  -- for any given server.  It does NOT control the absolute number of rows in the table.

  DECLARE @current_rows_per_server INT
  DECLARE @max_rows_per_server     INT -- This value comes from the resgistry (DownloadedMaxRows)
  DECLARE @rows_to_delete          INT
  DECLARE @quoted_server_name      NVARCHAR(514) -- enough room to accomodate the quoted name
  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @server_name = LTRIM(RTRIM(@server_name))

  -- Check the server name (if it's bad we fail silently)
  IF (@server_name IS NULL) OR
     (NOT EXISTS (SELECT *
                  FROM msdb.dbo.sysdownloadlist
                  WHERE (target_server = @server_name)))
    RETURN(1) -- Failure

  SELECT @max_rows_per_server = 0

  -- Get the max-rows-per-server from the registry
  EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
                                         N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
                                         N'DownloadedMaxRows',
                                         @max_rows_per_server OUTPUT,
                                         N'no_output'

  -- Check if we are limiting sysdownloadlist rows
  IF (ISNULL(@max_rows_per_server, -1) = -1)
    RETURN

  -- Check that max_rows_per_server is >= 0
  IF (@max_rows_per_server < -1)
  BEGIN
    -- It isn't, so default to 100 rows
    SELECT @max_rows_per_server = 100
    EXECUTE master.dbo.xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
                                            N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
                                            N'DownloadedMaxRows',
                                            N'REG_DWORD',
                                            @max_rows_per_server
  END

  -- Get the number of downloaded rows in sysdownloadlist for the target server in question
  -- NOTE: Determining this [quickly] requires a [non-clustered] index on target_server
  SELECT @current_rows_per_server = COUNT(*)
  FROM msdb.dbo.sysdownloadlist
  WHERE (target_server = @server_name)
    AND (status = 1)

  -- Delete the oldest downloaded row(s) for the target server in question if the new row has
  -- pushed us over the per-server row limit
  SELECT @rows_to_delete = @current_rows_per_server - @max_rows_per_server
  IF (@rows_to_delete > 0)
  BEGIN
    WITH RowsToDelete AS (
      SELECT TOP (@rows_to_delete) *
      FROM msdb.dbo.sysdownloadlist
      WHERE (target_server = @server_name)
        AND (status = 1)
      ORDER BY instance_id
    )
    DELETE FROM RowsToDelete;
  END
END
go

/**************************************************************/
/* SP_POST_MSX_OPERATION                                      */
/*                                                            */
/* NOTE: We define this procedure here instead of in the      */
/*      'Support procedures' section because of the many      */
/*       other procedures that reference it.                  */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_post_msx_operation...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = 'sp_post_msx_operation')
              AND (type = 'P')))
  DROP PROCEDURE sp_post_msx_operation
go
CREATE PROCEDURE sp_post_msx_operation
  @operation              VARCHAR(64),
  @object_type            VARCHAR(64)       = 'JOB',-- Can be JOB, SERVER or SCHEDULE
  @job_id                 UNIQUEIDENTIFIER  = NULL, -- NOTE: 0x00 means 'ALL' jobs
  @specific_target_server sysname           = NULL,
  @value                  INT               = NULL, -- For polling interval value
  @schedule_uid           UNIQUEIDENTIFIER  = NULL  -- schedule_uid if the @object_type = 'SCHEDULE'
AS
BEGIN
  DECLARE @operation_code            INT
  DECLARE @specific_target_server_id INT
  DECLARE @instructions_posted       INT
  DECLARE @job_id_as_char            VARCHAR(36)
  DECLARE @schedule_uid_as_char      VARCHAR(36)
  DECLARE @msx_time_zone_adjustment  INT
  DECLARE @local_machine_name        sysname
  DECLARE @retval                    INT

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @operation              = LTRIM(RTRIM(@operation))
  SELECT @object_type            = LTRIM(RTRIM(@object_type))
  SELECT @specific_target_server = LTRIM(RTRIM(@specific_target_server))

  -- Turn [nullable] empty string parameters into NULLs
  IF (@specific_target_server = N'') SELECT @specific_target_server = NULL

  -- Only a sysadmin can do this, but fail silently for a non-sysadmin
  IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) 
    RETURN(0) -- Success (or more accurately a no-op)

  -- Check operation
  SELECT @operation = UPPER(@operation collate SQL_Latin1_General_CP1_CS_AS)
  SELECT @operation_code = CASE @operation
                             WHEN 'INSERT'    THEN 1
                             WHEN 'UPDATE'    THEN 2
                             WHEN 'DELETE'    THEN 3
                             WHEN 'START'     THEN 4
                             WHEN 'STOP'      THEN 5
                             WHEN 'RE-ENLIST' THEN 6
                             WHEN 'DEFECT'    THEN 7
                             WHEN 'SYNC-TIME' THEN 8
                             WHEN 'SET-POLL'  THEN 9
                             ELSE 0
                           END
  IF (@operation_code = 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@operation_code', 'INSERT, UPDATE, DELETE, START, STOP, RE-ENLIST, DEFECT, SYNC-TIME, SET-POLL')
    RETURN(1) -- Failure
  END

  -- Check object type (in 9.0 only 'JOB', 'SERVER' or 'SCHEDULE'are valid)
  IF ((@object_type <> 'JOB') AND (@object_type <> 'SERVER') AND (@object_type <> 'SCHEDULE'))
  BEGIN
    RAISERROR(14266, -1, -1, '@object_type', 'JOB, SERVER, SCHEDULE')
    RETURN(1) -- Failure
  END

  -- Check that for a object type of JOB a job_id has been supplied
  IF ((@object_type = 'JOB') AND (@job_id IS NULL))
  BEGIN
    RAISERROR(14233, -1, -1)
    RETURN(1) -- Failure
  END
  
    -- Check that for a object type of JOB a job_id has been supplied
  IF ((@object_type = 'SCHEDULE') AND (@schedule_uid IS NULL))
  BEGIN
    RAISERROR(14365, -1, -1)
    RETURN(1) -- Failure
  END

  -- Check polling interval value
  IF (@operation_code = 9) AND ((ISNULL(@value, 0) < 10) OR (ISNULL(@value, 0) > 28800))
  BEGIN
    RAISERROR(14266, -1, -1, '@value', '10..28800')
    RETURN(1) -- Failure
  END

  -- Check specific target server
  IF (@specific_target_server IS NOT NULL)
  BEGIN
    SELECT @specific_target_server = UPPER(@specific_target_server)

    -- Check if the local server is being targeted
    IF (@specific_target_server = UPPER(CONVERT(sysname, SERVERPROPERTY('ServerName'))))
    BEGIN
      RETURN(0)
    END
    ELSE
    BEGIN
      SELECT @specific_target_server_id = server_id
      FROM msdb.dbo.systargetservers
      WHERE (UPPER(server_name) = @specific_target_server)
      IF (@specific_target_server_id IS NULL)
      BEGIN
        RAISERROR(14262, -1, -1, '@specific_target_server', @specific_target_server)
        RETURN(1) -- Failure
      END
    END
  END

  -- Check that this server is an MSX server
  IF ((SELECT COUNT(*)
       FROM msdb.dbo.systargetservers) = 0)
  BEGIN
    RETURN(0)
  END

  -- Get local machine name
  EXECUTE @retval = master.dbo.xp_getnetname @local_machine_name OUTPUT
  IF (@retval <> 0) OR (@local_machine_name IS NULL)
  BEGIN
    RAISERROR(14225, -1, -1)
    RETURN(1)
  END

  -- Job-specific processing...
  IF (@object_type = 'JOB')
  BEGIN
    -- Validate the job (if supplied)
    IF (@job_id <> CONVERT(UNIQUEIDENTIFIER, 0x00))
    BEGIN
      SELECT @job_id_as_char = CONVERT(VARCHAR(36), @job_id)

      -- Check if the job exists
      IF (NOT EXISTS (SELECT *
                      FROM msdb.dbo.sysjobs_view
                      WHERE (job_id = @job_id)))
      BEGIN
        RAISERROR(14262, -1, -1, '@job_id', @job_id_as_char)
        RETURN(1) -- Failure
      END

      -- If this is a local job then there's nothing for us to do
      IF (EXISTS (SELECT *
                  FROM msdb.dbo.sysjobservers
                  WHERE (job_id = @job_id)
                    AND (server_id = 0))) -- 0 means local server
      OR (NOT EXISTS (SELECT *
                      FROM msdb.dbo.sysjobservers
                      WHERE (job_id = @job_id)))
      BEGIN
        RETURN(0)
      END
    END

    -- Generate the sysdownloadlist row(s)...
    IF (@operation_code = 1) OR  -- Insert
       (@operation_code = 2) OR  -- Update
       (@operation_code = 3) OR  -- Delete
       (@operation_code = 4) OR  -- Start
       (@operation_code = 5)     -- Stop
    BEGIN
      IF (@job_id = CONVERT(UNIQUEIDENTIFIER, 0x00)) -- IE. 'ALL'
      BEGIN
        -- All jobs

        -- Handle DELETE as a special case (rather than posting 1 instruction per job we just
        -- post a single instruction that means 'delete all jobs from the MSX')
        IF (@operation_code = 3)
        BEGIN
          INSERT INTO msdb.dbo.sysdownloadlist
                (source_server,
                 operation_code,
                 object_type,
                 object_id,
                 target_server)
          SELECT @local_machine_name,
                 @operation_code,
                 1,                -- 1 means 'JOB'
                 CONVERT(UNIQUEIDENTIFIER, 0x00),
                 sts.server_name
          FROM systargetservers sts
          WHERE ((@specific_target_server_id IS NULL) OR (sts.server_id = @specific_target_server_id))
            AND ((SELECT COUNT(*)
                  FROM msdb.dbo.sysjobservers
                  WHERE (server_id = sts.server_id)) > 0)
          SELECT @instructions_posted = @@rowcount
        END
        ELSE
        BEGIN
          INSERT INTO msdb.dbo.sysdownloadlist
                (source_server,
                 operation_code,
                 object_type,
                 object_id,
                 target_server)
          SELECT @local_machine_name,
                 @operation_code,
                 1,                -- 1 means 'JOB'
                 sjv.job_id,
                 sts.server_name
          FROM sysjobs_view     sjv,
               sysjobservers    sjs,
               systargetservers sts
          WHERE (sjv.job_id = sjs.job_id)
            AND (sjs.server_id = sts.server_id)
            AND (sjs.server_id <> 0) -- We want to exclude local jobs
            AND ((@specific_target_server_id IS NULL) OR (sjs.server_id = @specific_target_server_id))
          SELECT @instructions_posted = @@rowcount
        END
      END
      ELSE
      BEGIN
        -- Specific job (ie. @job_id is not 0x00)
        INSERT INTO msdb.dbo.sysdownloadlist
              (source_server,
               operation_code,
               object_type,
               object_id,
               target_server,
               deleted_object_name)
        SELECT @local_machine_name,
               @operation_code,
               1,                -- 1 means 'JOB'
               sjv.job_id,
               sts.server_name,
               CASE @operation_code WHEN 3 -- Delete
                                      THEN sjv.name
                                      ELSE NULL
                                    END
        FROM sysjobs_view     sjv,
             sysjobservers    sjs,
             systargetservers sts
        WHERE (sjv.job_id = @job_id)
          AND (sjv.job_id = sjs.job_id)
          AND (sjs.server_id = sts.server_id)
          AND (sjs.server_id <> 0) -- We want to exclude local jobs
          AND ((@specific_target_server_id IS NULL) OR (sjs.server_id = @specific_target_server_id))
        SELECT @instructions_posted = @@rowcount
      END
    END
    ELSE
    BEGIN
      RAISERROR(14266, -1, -1, '@operation_code', 'INSERT, UPDATE, DELETE, START, STOP')
      RETURN(1) -- Failure
    END
  END
  
  
  -- SCHEDULE specific processing for INSERT, UPDATE or DELETE schedule operations
  -- All msx jobs that use the specified @schedule_uid will be notified with an Insert operation. 
  -- This will cause agent to reload all schedules for each job. 
  -- This is compatible with the legacy shiloh servers that don't know about reusable schedules
  IF (@object_type = 'SCHEDULE')
  BEGIN
    -- Validate the schedule
    -- Check if the schedule exists
    IF (NOT EXISTS (SELECT *
                    FROM msdb.dbo.sysschedules_localserver_view
                    WHERE (schedule_uid = @schedule_uid)))
    BEGIN
      SELECT @schedule_uid_as_char = CONVERT(VARCHAR(36), @schedule_uid)
      
      RAISERROR(14262, -1, -1, '@schedule_uid', @schedule_uid_as_char)
      RETURN(1) -- Failure
    END

    -- If this schedule is only used locally (no target servers) then there's nothing to do
    IF (NOT EXISTS (SELECT *
                    FROM msdb.dbo.sysschedules    s,
                        msdb.dbo.sysjobschedules  js,
                        msdb.dbo.sysjobs_view     sjv,
                        msdb.dbo.sysjobservers    sjs,
                        msdb.dbo.systargetservers sts
                    WHERE (s.schedule_uid = @schedule_uid)
                    AND (s.schedule_id = js.schedule_id)
                    AND (sjv.job_id = js.job_id)
                    AND (sjv.job_id = sjs.job_id)
                    AND (sjs.server_id = sts.server_id)
                    AND (sjs.server_id <> 0)))                        
    BEGIN
      RETURN(0)
    END

    -- Generate the sysdownloadlist row(s)...
    IF (@operation_code = 1) OR  -- Insert
       (@operation_code = 2) OR  -- Update
       (@operation_code = 3)     -- Delete
    BEGIN
      -- Insert specific schedule into sysdownloadlist 
      -- We need to create a sysdownloadlist JOB INSERT record for each job that runs the schedule
     INSERT INTO msdb.dbo.sysdownloadlist
         (source_server,
          operation_code,
          object_type,
          object_id,
          target_server)
     SELECT @local_machine_name,
          1,             -- 1 means 'Insert'
          1,             -- 1 means 'JOB'
          sjv.job_id,
          sts.server_name
     FROM msdb.dbo.sysschedules     s,
           msdb.dbo.sysjobschedules  js,
           msdb.dbo.sysjobs_view     sjv,
         msdb.dbo.sysjobservers    sjs,
         systargetservers          sts
     WHERE (s.schedule_id = js.schedule_id)
        AND (js.job_id = sjv.job_id)
        AND (sjv.job_id = sjs.job_id)
      AND (sjs.server_id = sts.server_id)
        AND (s.schedule_uid = @schedule_uid)
      AND (sjs.server_id <> 0)            -- We want to exclude local jobs
      AND ((@specific_target_server_id IS NULL) OR (sjs.server_id = @specific_target_server_id))

      SELECT @instructions_posted = @@rowcount


    END
    ELSE
    BEGIN
      RAISERROR(14266, -1, -1, '@operation_code', 'UPDATE, DELETE')
      RETURN(1) -- Failure
    END
  END
  

  -- Server-specific processing...
  IF (@object_type = 'SERVER')
  BEGIN
    -- Generate the sysdownloadlist row(s)...
    IF (@operation_code = 6) OR  -- ReEnlist
       (@operation_code = 7) OR  -- Defect
       (@operation_code = 8) OR  -- Synchronize time (with MSX)
       (@operation_code = 9)     -- Set MSX polling interval (in seconds)
    BEGIN
      IF (@operation_code = 8)
      BEGIN
        EXECUTE master.dbo.xp_regread N'HKEY_LOCAL_MACHINE',
                                      N'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
                                      N'Bias',
                                      @msx_time_zone_adjustment OUTPUT,
                                      N'no_output'
        SELECT @msx_time_zone_adjustment = -ISNULL(@msx_time_zone_adjustment, 0)
      END

      INSERT INTO msdb.dbo.sysdownloadlist
            (source_server,
             operation_code,
             object_type,
             object_id,
             target_server)
      SELECT @local_machine_name,
             @operation_code,
             2,                  -- 2 means 'SERVER'
             CASE @operation_code
               WHEN 8 THEN CONVERT(UNIQUEIDENTIFIER, CONVERT(BINARY(16), -(@msx_time_zone_adjustment - sts.time_zone_adjustment)))
               WHEN 9 THEN CONVERT(UNIQUEIDENTIFIER, CONVERT(BINARY(16), @value))
               ELSE CONVERT(UNIQUEIDENTIFIER, 0x00)
             END,
             sts.server_name
      FROM systargetservers sts
      WHERE ((@specific_target_server_id IS NULL) OR (sts.server_id = @specific_target_server_id))
      SELECT @instructions_posted = @@rowcount
    END
    ELSE
    BEGIN
      RAISERROR(14266, -1, -1, '@operation_code', 'RE-ENLIST, DEFECT, SYNC-TIME, SET-POLL')
      RETURN(1) -- Failure
    END
  END


  -- Report number of rows inserted
  IF (@object_type = 'JOB') AND
     (@job_id = CONVERT(UNIQUEIDENTIFIER, 0x00)) AND
     (@instructions_posted = 0) AND
     (@specific_target_server_id IS NOT NULL)
    RAISERROR(14231, 0, 1, '@specific_target_server', @specific_target_server)
  ELSE
    RAISERROR(14230, 0, 1, @instructions_posted, @operation)

  -- Delete any [downloaded] instructions that are over the registry-defined limit
  IF (@specific_target_server IS NOT NULL)
    EXECUTE msdb.dbo.sp_downloaded_row_limiter @specific_target_server

  RETURN(0) -- 0 means success
END
go

/**************************************************************/
/* SP_VERIFY_PERFORMANCE_CONDITION                            */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_performance_condition...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_performance_condition')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_performance_condition
go
CREATE PROCEDURE sp_verify_performance_condition
  @performance_condition NVARCHAR(512)
AS
BEGIN
  DECLARE @delimiter_count INT
  DECLARE @temp_str        NVARCHAR(512)
  DECLARE @object_name     sysname
  DECLARE @counter_name    sysname
  DECLARE @instance_name   sysname
  DECLARE @pos             INT

  SET NOCOUNT ON
  
  -- The performance condition must have the format 'object|counter|instance|comparator|value'
  -- NOTE: 'instance' may be empty.
  IF (PATINDEX(N'%_|%_|%|[><=]|[0-9]%', @performance_condition) = 0)
  BEGIN
    RAISERROR(14507, 16, 1)
    RETURN(1) -- Failure
  END

  -- Parse the performance_condition
  SELECT @delimiter_count = 0
  SELECT @temp_str = @performance_condition
  SELECT @pos = CHARINDEX(N'|', @temp_str)
  WHILE (@pos <> 0)
  BEGIN
    SELECT @delimiter_count = @delimiter_count + 1
    IF (@delimiter_count = 1) SELECT @object_name = SUBSTRING(@temp_str, 1, @pos - 1)
    IF (@delimiter_count = 2) SELECT @counter_name = SUBSTRING(@temp_str, 1, @pos - 1)
    IF (@delimiter_count = 3) SELECT @instance_name = SUBSTRING(@temp_str, 1, @pos - 1)
    SELECT @temp_str = SUBSTRING(@temp_str, @pos + 1, (DATALENGTH(@temp_str) / 2) - @pos)
    SELECT @pos = CHARINDEX(N'|', @temp_str)
  END
  IF (@delimiter_count <> 4)
  BEGIN
    RAISERROR(14507, 16, 1)
    RETURN(1) -- Failure
  END

  -- Check the object_name
  IF (NOT EXISTS (SELECT *
                  FROM master.dbo.sysperfinfo
                  WHERE (object_name = @object_name)))
  BEGIN
    RAISERROR(14262, 16, 1, 'object_name', @object_name)
    RETURN(1) -- Failure
  END

  -- Check the counter_name
  IF (NOT EXISTS (SELECT *
                  FROM master.dbo.sysperfinfo
                  WHERE (object_name = @object_name)
                    AND (counter_name = @counter_name)))
  BEGIN
    RAISERROR(14262, 16, 1, 'counter_name', @counter_name)
    RETURN(1) -- Failure
  END

  -- Check the instance_name
  IF (@instance_name IS NOT NULL)
  BEGIN
    IF (NOT EXISTS (SELECT *
                    FROM master.dbo.sysperfinfo
                    WHERE (object_name = @object_name)
                      AND (counter_name = @counter_name)
                      AND (instance_name = @instance_name)))
    BEGIN
      RAISERROR(14262, 16, 1, 'instance_name', @instance_name)
      RETURN(1) -- Failure
    END
  END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_VERIFY_JOB_DATE                                         */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_job_date...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_job_date')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_job_date
go
CREATE PROCEDURE sp_verify_job_date
  @date           INT,
  @date_name      VARCHAR(60) = 'date',
  @error_severity INT         = -1
AS
BEGIN
  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @date_name = LTRIM(RTRIM(@date_name))

  IF ((ISDATE(CONVERT(VARCHAR, @date)) = 0) OR (@date < 19900101) OR (@date > 99991231))
  BEGIN
    RAISERROR(14266, @error_severity, -1, @date_name, '19900101..99991231')
    RETURN(1) -- Failure
  END

  RETURN(0) -- Success
END
go

/**************************************************************/
/* SP_VERIFY_JOB_TIME                                         */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_job_time...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_job_time')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_job_time
go

CREATE PROCEDURE sp_verify_job_time
  @time           INT,
  @time_name      VARCHAR(60) = 'time',
  @error_severity INT = -1
AS
BEGIN
  DECLARE @hour      INT
  DECLARE @minute    INT
  DECLARE @second    INT
  DECLARE @part_name NVARCHAR(50)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @time_name = LTRIM(RTRIM(@time_name))

  IF ((@time < 0) OR (@time > 235959))
  BEGIN
    RAISERROR(14266, @error_severity, -1, @time_name, '000000..235959')
    RETURN(1) -- Failure
  END

  SELECT @hour   = (@time / 10000)
  SELECT @minute = (@time % 10000) / 100
  SELECT @second = (@time % 100)

  -- Check hour range
  IF (@hour > 23)
  BEGIN
    SELECT @part_name = FORMATMESSAGE(14218)
    RAISERROR(14287, @error_severity, -1, @time_name, @part_name)
    RETURN(1) -- Failure
  END

  -- Check minute range
  IF (@minute > 59)
  BEGIN
    SELECT @part_name = FORMATMESSAGE(14219)
    RAISERROR(14287, @error_severity, -1, @time_name, @part_name)
    RETURN(1) -- Failure
  END

  -- Check second range
  IF (@second > 59)
  BEGIN
    SELECT @part_name = FORMATMESSAGE(14220)
    RAISERROR(14287, @error_severity, -1, @time_name, @part_name)
    RETURN(1) -- Failure
  END

  RETURN(0) -- Success
END
go


/**************************************************************/
/* SP_VERIFY_ALERT                                            */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_verify_alert...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_verify_alert')
              AND (type = 'P')))
  DROP PROCEDURE sp_verify_alert
go
CREATE PROCEDURE sp_verify_alert
  @name                          sysname,
  @message_id                    INT,
  @severity                      INT,
  @enabled                       TINYINT,
  @delay_between_responses       INT,
  @notification_message          NVARCHAR(512),
  @include_event_description_in  TINYINT,
  @database_name                 sysname,
  @event_description_keyword     NVARCHAR(100),
  @job_id                        UNIQUEIDENTIFIER OUTPUT,
  @job_name                      sysname          OUTPUT,
  @occurrence_count              INT,
  @raise_snmp_trap               TINYINT,
  @performance_condition         NVARCHAR(512),
  @category_name                 sysname,
  @category_id                   INT              OUTPUT,
  @count_reset_date              INT,
  @count_reset_time              INT,
  @wmi_namespace      NVARCHAR(512),      -- New for 9.0
  @wmi_query          NVARCHAR(512),      -- New for 9.0
  @event_id        INT     OUTPUT   -- New for 9.0
AS
BEGIN
  DECLARE @retval               INT
  DECLARE @non_alertable_errors VARCHAR(512)
  DECLARE @message_id_as_string VARCHAR(10)
  DECLARE @res_valid_range      NVARCHAR(100)
  DECLARE @alert_no_wmi_check   INT
  DECLARE @job_owner_sid      VARBINARY(85)

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @name                      = LTRIM(RTRIM(@name))
  SELECT @notification_message      = LTRIM(RTRIM(@notification_message))
  SELECT @database_name             = LTRIM(RTRIM(@database_name))
  SELECT @event_description_keyword = LTRIM(RTRIM(@event_description_keyword))
  SELECT @job_name                  = LTRIM(RTRIM(@job_name))
  SELECT @performance_condition     = LTRIM(RTRIM(@performance_condition))
  SELECT @category_name             = LTRIM(RTRIM(@category_name))
  SELECT @alert_no_wmi_check        = 0
  
  -- Only a sysadmin can do this
  
  IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1))
  BEGIN
    RAISERROR(15003, 16, 1, N'sysadmin')
    RETURN(1) -- Failure
  END

  -- Check if the NewName is unique
  IF (EXISTS (SELECT *
              FROM msdb.dbo.sysalerts
              WHERE (name = @name)))
  BEGIN
    RAISERROR(14261, 16, 1, '@name', @name)
    RETURN(1) -- Failure
  END

  -- Check if the user has supplied MessageID OR Severity OR Performance-Condition OR WMI namespace/query
  IF ((@performance_condition IS NULL) AND (@message_id = 0) AND (@severity = 0) AND ((@wmi_namespace IS NULL) OR (@wmi_query IS NULL))) OR
     ((@performance_condition IS NOT NULL) AND ((@message_id <> 0) OR (@severity <> 0) OR (@wmi_namespace IS NOT NULL) OR (@wmi_query IS NOT NULL))) OR
     ((@message_id <> 0) AND ((@performance_condition IS NOT NULL) OR (@severity <> 0) OR (@wmi_namespace IS NOT NULL) OR (@wmi_query IS NOT NULL))) OR
     ((@severity <> 0) AND ((@performance_condition IS NOT NULL) OR (@message_id <> 0) OR (@wmi_namespace IS NOT NULL) OR (@wmi_query IS NOT NULL)))
  BEGIN
    RAISERROR(14500, 16, 1)
    RETURN(1) -- Failure
  END

  -- Check the Severity
  IF ((@severity < 0) OR (@severity > 25))
  BEGIN
    RAISERROR(14266, 16, 1, '@severity', '0..25')
    RETURN(1) -- Failure
  END

  -- Check the MessageID
  IF (@message_id <> 0) AND
     (NOT EXISTS (SELECT error
                  FROM master.dbo.sysmessages
                  WHERE (error = @message_id)))
  BEGIN
    SELECT @message_id_as_string = CONVERT(VARCHAR, @message_id)
    RAISERROR(14262, 16, 1, '@message_id', @message_id_as_string)
    RETURN(1) -- Failure
  END

  -- Check if it is legal to set an alert on this MessageID
  DECLARE @TempRetVal TABLE (RetVal INT)
  EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
                                         N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
                                         N'NonAlertableErrors',
                                         @non_alertable_errors OUTPUT,
                                         N'no_output'
  IF (ISNULL(@non_alertable_errors, N'NULL') <> N'NULL')
  BEGIN
    DECLARE @message_id_as_char VARCHAR(10)

    SELECT @message_id_as_char = CONVERT(VARCHAR(10), @message_id)
    INSERT INTO @TempRetVal
    EXECUTE ('IF (' + @message_id_as_char + ' IN (' + @non_alertable_errors + ')) SELECT 1')
  END

  IF (EXISTS (SELECT *
              FROM @TempRetVal))
  BEGIN
    RAISERROR(14506, 16, 1, @message_id)
    RETURN(1) -- Failure
  END

  -- Enabled must be 0 or 1
  IF (@enabled NOT IN (0, 1))
  BEGIN
    RAISERROR(14266, 16, 1, '@enabled', '0, 1')
    RETURN(1) -- Failure
  END

  -- DelayBetweenResponses must be > 0
  IF (@delay_between_responses < 0)
  BEGIN
    SELECT @res_valid_range = FORMATMESSAGE(14206)
    RAISERROR(14266, 16, 1, '@delay_between_responses', @res_valid_range)
    RETURN(1) -- Failure
  END

  -- NOTE: We don't check the notification message

  -- Check IncludeEventDescriptionIn
  IF ((@include_event_description_in < 0) OR (@include_event_description_in > 7))
  BEGIN
    SELECT @res_valid_range = FORMATMESSAGE(14208)
    RAISERROR(14266, 16, 1, '@include_event_description_in', @res_valid_range)
    RETURN(1) -- Failure
  END

  -- Check the database name
  IF (@database_name IS NOT NULL) AND (DB_ID(@database_name) IS NULL)
  BEGIN
    RAISERROR(15010, 16, 1, @database_name)
    RETURN(1) -- Failure
  END

  -- NOTE: We don't check the event description keyword

  -- Check JobName/ID
  IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL))
  BEGIN
    -- We use '' as a special value which means 'no job' (we cannot use NULL since this forces
    -- sp_update_alert to use the existing value)
    IF (@job_name = N'')
      SELECT @job_id = 0x00
    ELSE
    BEGIN
      EXECUTE @retval = sp_verify_job_identifiers '@job_name',
                                                  '@job_id',
                                                   @job_name OUTPUT,
                                                   @job_id   OUTPUT,
                                       @owner_sid = @job_owner_sid OUTPUT
      IF (@retval <> 0)
        RETURN(1) -- Failure
        
     -- Check permissions beyond what's checked by the sysjobs_view
     -- SQLAgentReaderRole and SQLAgentOperatorRole can see all jobs but
     -- cannot modify them
     IF (@job_owner_sid <> SUSER_SID()                   -- does not own the job
        AND (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1))   -- is not sysadmin
     BEGIN
       RAISERROR(14525, -1, -1); 
       RETURN(1) -- Failure
     END
        
      -- Check that the job is a local job
      IF (NOT EXISTS (SELECT *
                      FROM msdb.dbo.sysjobservers
                      WHERE (job_id = @job_id)
                        AND (server_id = 0)))
      BEGIN
        RAISERROR(14527, -1, -1, @job_name)
        RETURN(1) -- Failure
      END
    END
  END

  -- OccurrenceCount must be > 0
  IF (@occurrence_count < 0)
  BEGIN
    RAISERROR(14266, 16, 1, '@occurrence_count', '0..n')
    RETURN(1) -- Failure
  END

  -- RaiseSNMPTrap must be 0 or 1
  IF (@raise_snmp_trap NOT IN (0, 1))
  BEGIN
    RAISERROR(14266, 16, 1, '@raise_snmp_trap', '0, 1')
    RETURN(1) -- Failure
  END

  -- Check the performance condition (including invalid parameter combinations)
  IF (@performance_condition IS NOT NULL)
  BEGIN
    IF (@database_name IS NOT NULL)
    BEGIN
      RAISERROR(14505, 16, 1, '@database_name')
      RETURN(1) -- Failure
    END

    IF (@event_description_keyword IS NOT NULL)
    BEGIN
      RAISERROR(14505, 16, 1, '@event_description_keyword')
      RETURN(1) -- Failure
    END
    
    IF (@wmi_namespace IS NOT NULL)
    BEGIN
      RAISERROR(14505, 16, 1, '@wmi_namespace')
      RETURN(1) -- Failure
    END

    IF (@wmi_query IS NOT NULL)
    BEGIN
      RAISERROR(14505, 16, 1, '@wmi_query')
      RETURN(1) -- Failure
    END

    -- Verify the performance condition
    EXECUTE @retval = msdb.dbo.sp_verify_performance_condition @performance_condition
    IF (@retval <> 0)
      RETURN(1) -- Failure
  END

  -- Check category name
  IF (@category_name = N'[DEFAULT]')
    SELECT @category_id = 98
  ELSE
  BEGIN
    SELECT @category_id = category_id
    FROM msdb.dbo.syscategories
    WHERE (category_class = 2) -- Alerts
      AND (category_type = 3) -- None
      AND (name = @category_name)
  END
  IF (@category_id IS NULL)
  BEGIN
    RAISERROR(14262, -1, -1, '@category_name', @category_name)
    RETURN(1) -- Failure
  END

  -- Check count reset date
  IF (@count_reset_date <> 0)
  BEGIN
    EXECUTE @retval = msdb.dbo.sp_verify_job_date @count_reset_date, '@count_reset_date'
    IF (@retval <> 0)
      RETURN(1) -- Failure
  END

  -- Check count reset time
  IF (@count_reset_time <> 0)
  BEGIN
    EXECUTE @retval = msdb.dbo.sp_verify_job_time @count_reset_time, '@count_reset_time'
    IF (@retval <> 0)
      RETURN(1) -- Failure
  END

  -- Check WMI parameters. Both must exist
  IF (@wmi_namespace IS NOT NULL)
  BEGIN
    IF (@wmi_query IS NULL)
   BEGIN
      RAISERROR(14509, 16, 1, '@wmi_query') 
     RETURN(1) -- Failure
   END
   
    IF (@database_name IS NOT NULL)
    BEGIN
      RAISERROR(14510, 16, 1, '@database_name') 
      RETURN(1) -- Failure
    END

    IF (@event_description_keyword IS NOT NULL)
    BEGIN
      RAISERROR(14510, 16, 1, '@event_description_keyword')
      RETURN(1) -- Failure
    END

    --do not check WMI properties if a registry setting is present
    EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
                                           N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
                                           N'AlertNoWmiCheck',
                                           @alert_no_wmi_check OUTPUT,
                                           'no_output'
    if (@alert_no_wmi_check <> 1)
    BEGIN
      EXECUTE @retval = msdb.dbo.sp_sqlagent_notify @op_type = N'T',
                    @wmi_namespace = @wmi_namespace,
               @wmi_query  = @wmi_query,
               @error_flag = 0
      IF (@retval <> 0)
     BEGIN
       RAISERROR(14511, 16, 1)
         RETURN(1) -- Failure
     END
    END

   -- Set event_id to indicate WMI alert   
    SELECT @event_id = 8
  END
  ELSE IF (@wmi_query IS NOT NULL)
  BEGIN
    RAISERROR(14512, 16, 1, '@wmi_namespace')
    RETURN(1) -- Failure
  END
  
  RETURN(0) -- Success
END
go


/**************************************************************/
/* SP_UPDATE_ALERT                                            */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_update_alert...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_update_alert')
              AND (type = 'P')))
  DROP PROCEDURE sp_update_alert
go
CREATE PROCEDURE sp_update_alert
  @name                         sysname,
  @new_name                     sysname          = NULL,
  @enabled                      TINYINT          = NULL,
  @message_id                   INT              = NULL,
  @severity                     INT              = NULL,
  @delay_between_responses      INT              = NULL,
  @notification_message         NVARCHAR(512)    = NULL,
  @include_event_description_in TINYINT          = NULL, -- 0 = None, 1 = Email, 2 = Pager. 4 = NetSend, 7 = All
  @database_name                sysname          = NULL,
  @event_description_keyword    NVARCHAR(100)    = NULL,
  @job_id                       UNIQUEIDENTIFIER = NULL, -- If provided must NOT also provide job_name
  @job_name                     sysname          = NULL, -- If provided must NOT also provide job_id
  @occurrence_count             INT              = NULL, -- Can only be set to 0
  @count_reset_date             INT              = NULL,
  @count_reset_time             INT              = NULL,
  @last_occurrence_date         INT              = NULL, -- Can only be set to 0
  @last_occurrence_time         INT              = NULL, -- Can only be set to 0
  @last_response_date           INT              = NULL, -- Can only be set to 0
  @last_response_time           INT              = NULL, -- Can only be set to 0
  @raise_snmp_trap              TINYINT          = NULL,
  @performance_condition        NVARCHAR(512)    = NULL, -- New for 7.0
  @category_name                sysname          = NULL, -- New for 7.0
  @wmi_namespace           sysname         = NULL, -- New for 9.0
  @wmi_query               NVARCHAR(512)   = NULL  -- New for 9.0
AS
BEGIN
  DECLARE @x_enabled                   TINYINT
  DECLARE @x_message_id                INT
  DECLARE @x_severity                  INT
  DECLARE @x_delay_between_responses   INT
  DECLARE @x_notification_message      NVARCHAR(512)
  DECLARE @x_include_event_description TINYINT
  DECLARE @x_database_name             sysname
  DECLARE @x_event_description_keyword NVARCHAR(100)
  DECLARE @x_occurrence_count          INT
  DECLARE @x_count_reset_date          INT
  DECLARE @x_count_reset_time          INT
  DECLARE @x_last_occurrence_date      INT
  DECLARE @x_last_occurrence_time      INT
  DECLARE @x_last_response_date        INT
  DECLARE @x_last_response_time        INT
  DECLARE @x_flags                     INT
  DECLARE @x_performance_condition     NVARCHAR(512)
  DECLARE @x_job_id                    UNIQUEIDENTIFIER
  DECLARE @x_category_id               INT
  DECLARE @x_event_id                  INT
  DECLARE @x_wmi_namespace          sysname
  DECLARE @x_wmi_query              NVARCHAR(512)

  DECLARE @include_event_desc_code     TINYINT
  DECLARE @return_code                 INT
  DECLARE @duplicate_name              sysname
  DECLARE @category_id                 INT
  DECLARE @alert_id                    INT
  DECLARE @cached_attribute_modified   INT
  DECLARE @event_id                 INT

  SET NOCOUNT ON

  -- Remove any leading/trailing spaces from parameters
  SELECT @new_name                  = LTRIM(RTRIM(@new_name))
  SELECT @job_name                  = LTRIM(RTRIM(@job_name))
  SELECT @notification_message      = LTRIM(RTRIM(@notification_message))
  SELECT @database_name             = LTRIM(RTRIM(@database_name))
  SELECT @event_description_keyword = LTRIM(RTRIM(@event_description_keyword))
  SELECT @performance_condition     = LTRIM(RTRIM(@performance_condition))
  SELECT @category_name             = LTRIM(RTRIM(@category_name))

  -- Are we modifying an attribute which SQLServerAgent caches?
  IF ((@new_name                     IS NOT NULL) OR
      (@enabled                      IS NOT NULL) OR
      (@message_id                   IS NOT NULL) OR
      (@severity                     IS NOT NULL) OR
      (@delay_between_responses      IS NOT NULL) OR
      (@notification_message         IS NOT NULL) OR
      (@include_event_description_in IS NOT NULL) OR
      (@database_name                IS NOT NULL) OR
      (@event_description_keyword    IS NOT NULL) OR
      (@job_id                       IS NOT NULL) OR
      (@job_name                     IS NOT NULL) OR
      (@last_response_date           IS NOT NULL) OR
      (@last_response_time           IS NOT NULL) OR
      (@raise_snmp_trap              IS NOT NULL) OR
      (@performance_condition        IS NOT NULL) OR
      (@wmi_namespace             IS NOT NULL) OR
      (@wmi_query              IS NOT NULL))  
    SELECT @cached_attribute_modified = 1
  ELSE
    SELECT @cached_attribute_modified = 0

  -- Map a job_id of 0 to the real value we use to mean 'no job'
  IF (@job_id = CONVERT(UNIQUEIDENTIFIER, 0x00)) AND (@job_name IS NULL)
    SELECT @job_name = N''

  -- Only a sysadmin can do this
  IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1))
  BEGIN
    RAISERROR(15003, 16, 1, N'sysadmin')
    RETURN(1)
  END

  -- Check if SQLServerAgent is in the process of starting
  EXECUTE @return_code = msdb.dbo.sp_is_sqlagent_starting
  IF (@return_code <> 0)
    RETURN(1) -- Failure

  -- Check if this Alert exists
  IF (NOT EXISTS (SELECT *
                  FROM msdb.dbo.sysalerts
                  WHERE (name = @name)))
  BEGIN
    RAISERROR(14262, 16, 1, '@name', @name)
    RETURN(1)
  END

  -- Certain values (if supplied) may only be updated to 0
  IF (@occurrence_count <> 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@occurrence_count', '0')
    RETURN(1) -- Failure
  END
  IF (@last_occurrence_date <> 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@last_occurrence_date', '0')
    RETURN(1) -- Failure
  END
  IF (@last_occurrence_time <> 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@last_occurrence_time', '0')
    RETURN(1) -- Failure
  END
  IF (@last_response_date <> 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@last_response_date', '0')
    RETURN(1) -- Failure
  END
  IF (@last_response_time <> 0)
  BEGIN
    RAISERROR(14266, -1, -1, '@last_response_time', '0')
    RETURN(1) -- Failure
  END

  -- Get existing (@x_) values
  SELECT @alert_id                    = id,
         @x_enabled                   = enabled,
         @x_message_id                = message_id,
         @x_severity                  = severity,
         @x_delay_between_responses   = delay_between_responses,
         @x_notification_message      = notification_message,
         @x_include_event_description = include_event_description,
         @x_database_name             = database_name,
         @x_event_description_keyword = event_description_keyword,
         @x_occurrence_count          = occurrence_count,
         @x_count_reset_date          = count_reset_date,
         @x_count_reset_time          = count_reset_time,
         @x_job_id                    = job_id,
         @x_last_occurrence_date      = last_occurrence_date,
         @x_last_occurrence_time      = last_occurrence_time,
         @x_last_response_date        = last_response_date,
         @x_last_response_time        = last_response_time,
         @x_flags                     = flags,
         @x_performance_condition     = performance_condition,
         @x_category_id               = category_id,
       @x_event_id              = event_id
  FROM msdb.dbo.sysalerts
  WHERE (name = @name)
  
  SELECT @x_job_id = sjv.job_id
  FROM msdb.dbo.sysalerts    sa,
       msdb.dbo.sysjobs_view sjv
  WHERE (sa.job_id = sjv.job_id)
    AND (sa.name = @name)

  -- Fill out the values for all non-supplied parameters from the existsing values
  IF (@x_event_id = 8)
  BEGIN
   -- WMI alert type
   IF (@wmi_namespace IS NULL) SELECT @wmi_namespace = @x_database_name
   IF (@wmi_query IS NULL) SELECT @wmi_query = @x_performance_condition
  END
  ELSE
  BEGIN
   -- Non-WMI alert type
   IF (@database_name IS NULL) SELECT @database_name = @x_database_name
   IF (@performance_condition IS NULL) SELECT @performance_condition = @x_performance_condition
  END
   
  IF (@enabled                      IS NULL) SELECT @enabled                      = @x_enabled
  IF (@message_id                   IS NULL) SELECT @message_id                   = @x_message_id
  IF (@severity                     IS NULL) SELECT @severity                     = @x_severity
  IF (@delay_between_responses      IS NULL) SELECT @delay_between_responses      = @x_delay_between_responses
  IF (@notification_message         IS NULL) SELECT @notification_message         = @x_notification_message
  IF (@include_event_description_in IS NULL) SELECT @include_event_description_in = @x_include_event_description
  IF (@event_description_keyword    IS NULL) SELECT @event_description_keyword    = @x_event_description_keyword
  IF (@job_id IS NULL) AND (@job_name IS NULL) SELECT @job_id                     = @x_job_id
  IF (@occurrence_count             IS NULL) SELECT @occurrence_count             = @x_occurrence_count
  IF (@count_reset_date             IS NULL) SELECT @count_reset_date             = @x_count_reset_date
  IF (@count_reset_time             IS NULL) SELECT @count_reset_time             = @x_count_reset_time
  IF (@last_occurrence_date         IS NULL) SELECT @last_occurrence_date         = @x_last_occurrence_date
  IF (@last_occurrence_time         IS NULL) SELECT @last_occurrence_time         = @x_last_occurrence_time
  IF (@last_response_date           IS NULL) SELECT @last_response_date           = @x_last_response_date
  IF (@last_response_time           IS NULL) SELECT @last_response_time           = @x_last_response_time
  IF (@raise_snmp_trap              IS NULL) SELECT @raise_snmp_trap              = @x_flags & 0x1
  IF (@category_name                IS NULL) SELECT @category_name = name FROM msdb.dbo.syscategories WHERE (category_id = @x_category_id)

  IF (@category_name IS NULL)
  BEGIN
    SELECT @category_name = name
    FROM msdb.dbo.syscategories
    WHERE (category_id = 98)
  END

  -- Turn [nullable] empty string parameters into NULLs
  IF (@new_name                  = N'') SELECT @new_name                  = NULL
  IF (@notification_message      = N'') SELECT @notification_message      = NULL
  IF (@database_name             = N'') SELECT @database_name             = NULL
  IF (@event_description_keyword = N'') SELECT @event_description_keyword = NULL
  IF (@performance_condition     = N'') SELECT @performance_condition     = NULL
  IF (@wmi_namespace        = N'') SELECT @wmi_namespace         = NULL
  IF (@wmi_query            = N'') SELECT @wmi_query             = NULL

  -- Verify the Alert
  IF (@job_id = CONVERT(UNIQUEIDENTIFIER, 0x00))
    SELECT @job_id = NULL
  EXECUTE @return_code = sp_verify_alert @new_name,
                                         @message_id,
                                         @severity,
                                         @enabled,
                                         @delay_between_responses,
                                         @notification_message,
                                         @include_event_description_in,
                                         @database_name,
                                         @event_description_keyword,
                                         @job_id OUTPUT,
                                         @job_name OUTPUT,
                                         @occurrence_count,
                                         @raise_snmp_trap,
                                         @performance_condition,
                                         @category_name,
                                         @category_id OUTPUT,
                                         @count_reset_date,
                                         @count_reset_time,
                                         @wmi_namespace,
                                         @wmi_query,
                                     @event_id OUTPUT
  IF (@return_code <> 0)
    RETURN(1) -- Failure

  -- If the user didn't supply a NewName, use the old one.
  -- NOTE: This must be done AFTER sp_verify_alert.
  IF (@new_name IS NULL)
    SELECT @new_name = @name

  -- Turn the 1st 'flags' bit on or off accordingly
  IF (@raise_snmp_trap = 0)
    SELECT @x_flags = @x_flags & 0xFFFE
  ELSE
    SELECT @x_flags = @x_flags | 0x0001

  -- For WMI alerts replace 
  -- database_name with wmi_namespace and 
  -- performance_conditon with wmi_query
  -- so we can store them in those columns in sysalerts table
  IF (@event_id = 8)
  BEGIN
   SELECT @database_name = @wmi_namespace
   SELECT @performance_condition = @wmi_query
  END

  -- Check if this Alert already exists
  SELECT @duplicate_name = FORMATMESSAGE(14205)
  SELECT @duplicate_name = name
  FROM msdb.dbo.sysalerts
  WHERE ((event_id = 8) AND 
       (ISNULL(performance_condition, N'') = ISNULL(@performance_condition, N'')) AND
       (ISNULL(database_name, N'') = ISNULL(@database_name, N''))) OR
      ((ISNULL(event_id,1) <> 8) AND 
       (ISNULL(performance_condition, N'apples') = ISNULL(@performance_condition, N'oranges'))) OR 
      ((performance_condition IS NULL) AND
         (message_id = @message_id) AND
         (severity = @severity) AND
         (ISNULL(database_name, N'') = ISNULL(@database_name, N'')) AND
         (ISNULL(event_description_keyword, N'') = ISNULL(@event_description_keyword, N'')))
  IF (@duplicate_name <> FORMATMESSAGE(14205) AND @duplicate_name <> @name)
  BEGIN
    RAISERROR(14501, 16, 1, @duplicate_name)
    RETURN(1) -- Failure
  END

  -- Finally, do the actual UPDATE
  UPDATE msdb.dbo.sysalerts
  SET name                        = @new_name,
      message_id                  = @message_id,
      severity                    = @severity,
      enabled                     = @enabled,
      delay_between_responses     = @delay_between_responses,
      notification_message        = @notification_message,
      include_event_description   = @include_event_description_in,
      database_name               = @database_name,
      event_description_keyword   = @event_description_keyword,
      job_id                      = ISNULL(@job_id, CONVERT(UNIQUEIDENTIFIER, 0x00)),
      occurrence_count            = @occurrence_count,
      count_reset_date            = @count_reset_date,
      count_reset_time            = @count_reset_time,
      last_occurrence_date        = @last_occurrence_date,
      last_occurrence_time        = @last_occurrence_time,
      last_response_date          = @last_response_date,
      last_response_time          = @last_response_time,
      flags                       = @x_flags,
      performance_condition       = @performance_condition,
      category_id                 = @category_id,
      event_id               = @event_id
  WHERE (name = @name)

  -- Notify SQLServerAgent of the change
  IF (@cached_attribute_modified = 1)
    EXECUTE msdb.dbo.sp_sqlagent_notify @op_type     = N'A',
                                        @alert_id    = @alert_id,
                                        @action_type = N'U'
  RETURN(0) -- Success
END
go


/**************************************************************/
/* SP_DELETE_JOB_REFERENCES                                   */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_delete_job_references...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_delete_job_references')
              AND (type = 'P')))
  DROP PROCEDURE sp_delete_job_references
go
CREATE PROCEDURE sp_delete_job_references
  @notify_sqlagent BIT = 1
AS
BEGIN
  DECLARE @deleted_job_id  UNIQUEIDENTIFIER
  DECLARE @task_id_as_char VARCHAR(10)
  DECLARE @job_is_cached   INT
  DECLARE @alert_name      sysname
  DECLARE @maintplan_plan_id  UNIQUEIDENTIFIER
  DECLARE @maintplan_subplan_id  UNIQUEIDENTIFIER

  -- Keep SQLServerAgent's cache in-sync and cleanup any 'webtask' cross-references to the deleted job(s)
  -- NOTE: The caller must have created a table called #temp_jobs_to_delete of the format
  --       (job_id UNIQUEIDENTIFIER NOT NULL, job_is_cached INT NOT NULL).

  DECLARE sqlagent_notify CURSOR LOCAL
  FOR
  SELECT job_id, job_is_cached
  FROM #temp_jobs_to_delete

  OPEN sqlagent_notify
  FETCH NEXT FROM sqlagent_notify INTO @deleted_job_id, @job_is_cached

  WHILE (@@fetch_status = 0)
  BEGIN
    -- NOTE: We only notify SQLServerAgent if we know the job has been cached
    IF(@job_is_cached = 1 AND @notify_sqlagent = 1)
      EXECUTE msdb.dbo.sp_sqlagent_notify @op_type     = N'J',
                                          @job_id      = @deleted_job_id,
                                          @action_type = N'D'

    IF (EXISTS (SELECT *
                FROM master.dbo.sysobjects
                WHERE (name = N'sp_cleanupwebtask')
                  AND (type = 'P')))
    BEGIN
      SELECT @task_id_as_char = CONVERT(VARCHAR(10), task_id)
      FROM msdb.dbo.systaskids
      WHERE (job_id = @deleted_job_id)
      IF (@task_id_as_char IS NOT NULL)
        EXECUTE ('master.dbo.sp_cleanupwebtask @taskid = ' + @task_id_as_char)
    END

    -- Maintenance plan cleanup for SQL 2005.
    -- If this job came from another server and it runs a subplan of a
    -- maintenance plan, then delete the subplan record. If that was
    -- the last subplan still referencing that plan, delete the plan.
    -- This removes a distributed maintenance plan from a target server
    -- once all of jobs from the master server that used that maintenance
    -- plan are deleted.
    SELECT @maintplan_plan_id = plans.plan_id, @maintplan_subplan_id = plans.subplan_id
    FROM sysmaintplan_subplans plans, sysjobs_view sjv
    WHERE plans.job_id = @deleted_job_id
      AND plans.job_id = sjv.job_id
      AND sjv.master_server = 1 -- This means the job came from the master

    IF (@maintplan_subplan_id is not NULL)
    BEGIN
      EXECUTE sp_maintplan_delete_subplan @subplan_id = @maintplan_subplan_id, @delete_jobs = 0
      IF (NOT EXISTS (SELECT *
                      FROM sysmaintplan_subplans
                      where plan_id = @maintplan_plan_id))
      BEGIN
        DECLARE @plan_name sysname

        SELECT @plan_name = name
          FROM sysmaintplan_plans
          WHERE id = @maintplan_plan_id

        EXECUTE sp_ssis_deletepackage @name = @plan_name, @folderid = '08aa12d5-8f98-4dab-a4fc-980b150a5dc8' -- this is the guid for 'Maintenance Plans'
      END
    END

    FETCH NEXT FROM sqlagent_notify INTO @deleted_job_id, @job_is_cached
  END
  DEALLOCATE sqlagent_notify

  -- Remove systaskid references (must do this AFTER sp_cleanupwebtask stuff)
  DELETE FROM msdb.dbo.systaskids
  WHERE job_id IN (SELECT job_id FROM #temp_jobs_to_delete)

  -- Remove sysdbmaintplan_jobs references (legacy maintenance plans prior to SQL 2005)
  DELETE FROM msdb.dbo.sysdbmaintplan_jobs
  WHERE job_id IN (SELECT job_id FROM #temp_jobs_to_delete)

  -- Finally, clean up any dangling references in sysalerts to the deleted job(s)
  DECLARE sysalerts_cleanup CURSOR LOCAL
  FOR
  SELECT name
  FROM msdb.dbo.sysalerts
  WHERE (job_id IN (SELECT job_id FROM #temp_jobs_to_delete))

  OPEN sysalerts_cleanup
  FETCH NEXT FROM sysalerts_cleanup INTO @alert_name
  WHILE (@@fetch_status = 0)
  BEGIN
    EXECUTE msdb.dbo.sp_update_alert @name   = @alert_name,
                                     @job_id = 0x00
    FETCH NEXT FROM sysalerts_cleanup INTO @alert_name
  END
  DEALLOCATE sysalerts_cleanup
END
go

/**************************************************************/
/* SP_DELETE_ALL_MSX_JOBS                                     */
/*                                                            */
/* NOTE: This is a separate procedure because SQLServerAgent  */
/*       needs to call it, as does sp_msx_defect and          */
/*       sp_delete_job.                                       */
/**************************************************************/

PRINT ''
PRINT 'Creating procedure sp_delete_all_msx_jobs...'
go
IF (EXISTS (SELECT *
            FROM msdb.dbo.sysobjects
            WHERE (name = N'sp_delete_all_msx_jobs')
              AND (type = 'P')))
  DROP PROCEDURE sp_delete_all_msx_jobs
go
CREATE PROCEDURE sp_delete_all_msx_jobs
  @msx_server   sysname,
  @jobs_deleted INT = NULL OUTPUT
AS
BEGIN
  SET NOCOUNT ON

  -- Change server name to always reflect real servername or servername\instancename
  IF (UPPER(@msx_server collate SQL_Latin1_General_CP1_CS_AS) = '(LOCAL)')
    SELECT @msx_server = UPPER(CONVERT(sysname, SERVERPROPERTY('ServerName')))

  -- Delete all the jobs that originated from the MSX
  -- Note: This temp table is referenced by msdb.dbo.sp_delete_job_references
