# Apex SQL ### Apex SQL Complete ApexSQL Complete can automatically fill in SQL keywords, statements, and identifiers. It integrates seamlessly with SSMS and helps with object script and description reviews without coding interruption and also speeds up SQL coding with snippets. This free SSMS can quickly reference the object’s script and description inline, format keywords and fill in fully qualified object names automatically. [Apex SQL Complete Introduction](https://www.apexsql.com/Video/youtube/complete/) With ApexSQL Complete you can: - Auto-complete SQL code directly in SQL Server Management Studio, including SSMS 17 - Identify the structure of complex SQL queries at a glance - Format auto-completed keywords in upper, lower or proper case - Specify aliases to be filled in for objects from all SQL Server instances and databases - Boost auto-complete performance with object caching [More Information](https://knowledgebase.apexsql.com/apexsql-complete-toc/) #### Install the Add-on The add on can be found locally on Adriano. The following path can be used:
```YAML \\Adriano\FileServer\CDRack\SQL_Apex\ApexSQLInstaller.exe ``` The add on must be installed using the default path. #### Configuring the signify Profile
Please note that SSMS must be closed before adding the configured files. In order to allow all user using the auto-complete add-on, a default signify profile has been configured. After the installation has been completed, the attached config package, ApexSQLComplete.zip, must be downloaded and copied to the user's local file directory.
Using the default installation path, the package must then be extracted to the following location: ```YAML C:\Users\[user]\AppData\Local\ApexSQL\ApexSQLComplete. ``` Within the files MyDefaults.xml and Options.xml replace the \[user\] with you domain user name to allow executed queries to be stored correctly to your computers file structure. Once the files have been replaced in this folder all setup will be ready for use after SSMS has been reopened. The following tools are now available: #### Auto Complete To insert auto-complete code the following insertion keys are available: - Space - Tab To show hints for typed code press **ctrl+space** #### Execution Alert In order to avoid dangerous updates from occurring on any DB, the following alerts have been configured to notify the user of such an action before continuing. [![image-1590520518781.png](https://signature.signifyhr.co.za/uploads/images/gallery/2020-05/scaled-1680-/VDImiGAkqN7ZXByh-image-1590520518781.png)](https://signature.signifyhr.co.za/uploads/images/gallery/2020-05/VDImiGAkqN7ZXByh-image-1590520518781.png) #### Snippets This is prepared code that can be inserted directly into the query with the basic building blocks required by typing the snippet key and clicking it: Table 1: SQL Snippets
Snippet keyDescription
TableCreateCreates a table with all the signify entity defaults columns added
FKCreateCheck for existence of foreign key and add if not exist as specified on [Add Foreign Key Constraint](http://shakespeare/SigniWiki/wiki/4735/add-foreign-key-constraint) page
#### Executed Query Log This is a log of all queries executed on the user's SSMS and are stored for the last 7 days. #### Tab Colouring The addition of tab colouring allows the user to immediately confirm on what server a query will be executed and the risk level of the execution. The following colouring has been configured: [![image-1590520605043.png](https://signature.signifyhr.co.za/uploads/images/gallery/2020-05/scaled-1680-/waBDxXIaI7ClexFm-image-1590520605043.png)](https://signature.signifyhr.co.za/uploads/images/gallery/2020-05/waBDxXIaI7ClexFm-image-1590520605043.png) #### Auto Replace The following auto replacements will be made for keys given followed by the space bar press Table 2: Auto Replacement Keys
Auto Replacement KeyReplacement
locWITH(NOLOCK)
selSELECT \* FROM
gdateGETDATE() BETWEEN ValidFrom and ValidTo
orderbORDER BY id DESC
ProcExistIF EXISTS (SELECT TOP 1 1 FROM sys.objects WHERE object\_id = OBJECT\_ID(N'myproc') AND type IN ( N'P', N'PC' ) ) DROP PROCEDURE myproc GO
TableExistIF (EXISTS (SELECT TOP 1 1 FROM INFORMATION\_SCHEMA.TABLES WHERE TABLE\_NAME = 'TheTable')) BEGIN /\*Do Stuff\*/ END
TempTableExistIF OBJECT\_ID('tempdb..#TheTable') IS NOT NULL BEGIN /\*Do Stuff\*/ END
ViewExistIF EXISTS(SELECT TOP 1 1 FROM sys.views WHERE name = 'TheView') BEGIN /\*Do Stuff\*/ END
FunctionExistIF EXISTS (SELECT TOP 1 1 FROM sys.objects WHERE object\_id = OBJECT\_ID(N'\[dbo\].\[FunctionName\]') AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' )) BEGIN /\* Do your stuff here \*/ END GO
IndexExistIF EXISTS(SELECT TOP 1 1 FROM sys.indexes WHERE name = 'IndexName' AND object\_id = OBJECT\_ID('TableName')) BEGIN /\* Do your stuff here \*/ END
DefaultExistIF NOT EXISTS (SELECT TOP 1 1 FROM sys.all\_columns c JOIN sys.tables t ON t.object\_id = c.object\_id JOIN sys.schemas s ON s.schema\_id = t.schema\_id JOIN sys.default\_constraints d ON c.default\_object\_id = d.object\_id WHERE t.name = 'TABLE\_NAME' AND c.name = 'COLUMN\_NAME' AND s.name = 'dbo') BEGIN /\* Do your stuff here \*/ END
CommentChanged{Date} : {Domain Username} : {Short description of change}
CommentCreated{Date} : {Domain Username} : {Short description of change}
StatExecUse SELECT execquery.last\_execution\_time AS \[Date Time\], execsql.text AS \[Script\] FROM sys.dm\_exec\_query\_stats AS execquery CROSS APPLY sys.dm\_exec\_sql\_text(execquery.sql\_handle) AS execsql ORDER BY execquery.last\_execution\_time DESC
StatProcSELECT TOP 1000 d.object\_id, d.database\_id, OBJECT\_NAME(object\_id, database\_id) 'proc name', d.cached\_time, d.last\_execution\_time, d.total\_elapsed\_time, d.total\_elapsed\_time/d.execution\_count AS \[avg\_elapsed\_time\], d.last\_elapsed\_time, d.execution\_count ,d.last\_elapsed\_time/(1024\*1024) as secondes, \[total\_worker\_time\] FROM sys.dm\_exec\_procedure\_stats AS d ORDER BY d.last\_elapsed\_time desc, \[total\_worker\_time\] DESC;
StatSessionSELECT r.start\_time \[Start Time\],session\_ID \[SPID\], DB\_NAME(database\_id) \[Database\], SUBSTRING(t.text,(r.statement\_start\_offset/2)+1, CASE WHEN statement\_end\_offset=-1 OR statement\_end\_offset=0 THEN (DATALENGTH(t.Text)-r.statement\_start\_offset/2)+1 ELSE (r.statement\_end\_offset-r.statement\_start\_offset)/2+1 END) \[Executing SQL\], Status,command,wait\_type,wait\_time,wait\_resource, last\_wait\_type FROM sys.dm\_exec\_requests r OUTER APPLY sys.dm\_exec\_sql\_text(sql\_handle) t WHERE session\_id != @@SPID don't show this query AND session\_id > 50 don't show system queries ORDER BY r.start\_time
StatHealthSELECT TOP 10000 record\_id ,dateadd(ms, - 1 \* (@ms\_ticks\_now - \[timestamp\]), GetDate()) AS EventTime ,SQLProcessUtilization ,SystemIdle ,100 - SystemIdle - SQLProcessUtilization AS OtherProcessUtilization FROM ( SELECT record.value('(./Record/@id)\[1\]', 'int') AS record\_id ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)\[1\]', 'int') AS SystemIdle ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)\[1\]', 'int') AS SQLProcessUtilization ,TIMESTAMP FROM ( SELECT TIMESTAMP ,convert(XML, record) AS record FROM sys.dm\_os\_ring\_buffers WHERE ring\_buffer\_type = N'RING\_BUFFER\_SCHEDULER\_MONITOR' AND record LIKE '%%' ) AS x ) AS y ORDER BY record\_id DESC
KillDBUSE master GO DECLARE @kill varchar(8000) = *;* SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';' FROM master..sysprocesses WHERE dbid = db\_id('SignifyHR\_ARMUAT\_CW\_Import\_NVE') EXEC(@kill); ALTER DATABASE SignifyHR\_ARMUAT\_CW\_Import\_NVE SET MULTI\_USER WITH ROLLBACK IMMEDIATE GO
ColumnExistIF EXISTS(SELECT TOP 1 1 FROM sys.columns WHERE Name = N'columnName' AND Object\_ID = Object\_ID(N'schemaName.tableName')) BEGIN Column Exists END
ConstraintExistIF EXISTS (SELECT TOP 1 1 FROM SYS.DEFAULT\_CONSTRAINTS WHERE OBJECT\_NAME(PARENT\_OBJECT\_ID) = 'RequisitionExternalCandidates' AND COL\_NAME(PARENT\_OBJECT\_ID, PARENT\_COLUMN\_ID) = 'CreatedDate') BEGIN /\*Do Stuff\*/ END
ScriptNameexec GenerateSQLFileName 'DomainUserName', 'ObjectName', 'SQLType', /\*(Optional)\*/'CommaDelimitedUsedByScripts'
RowNumROW\_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC)
ForeignKeyExistIF NOT EXISTS ( SELECT 1 FROM sys.foreign\_keys AS f INNER JOIN sys.foreign\_key\_columns AS fc ON f.OBJECT\_ID = fc.constraint\_object\_id INNER JOIN sys.tables t ON t.OBJECT\_ID = fc.referenced\_object\_id WHERE OBJECT\_NAME (f.referenced\_object\_id) = 'licLicenceReasons' AND OBJECT\_NAME(f.parent\_object\_id) = 'prsEmployeeLicences' AND COL\_NAME(fc.parent\_object\_id,fc.parent\_column\_id) = 'licLicenceReasonId' ) ALTER TABLE prsEmployeeLicences ADD CONSTRAINT FK\_prsEmployeeLicences\_licLicenceReasons FOREIGN KEY (licLicenceReasonId) REFERENCES licLicenceReasons(Id) GO
ObjectExist/\* C = CHECK constraint D = Default or DEFAULT constraint F = FOREIGN KEY constraint L = Log FN = Scalar function IF = Inlined table-function P = Stored procedure PK = PRIMARY KEY constraint (type is K) RF = Replication filter stored procedure S = System table TF = Table function TR = Trigger U = User table UQ = UNIQUE constraint (type is K) V = View X = Extended stored procedure - / IF (OBJECT\_ID('tempdb..#tmpjpImportUpdateData', 'U') IS NOT NULL) BEGIN END
SchemaCursorDECLARE @SchemaID INT DECLARE curs CURSOR FAST\_FORWARD FOR SELECT SchemaID FROM cfgSchemaID WITH(NOLOCK) WHERE GETDATE() BETWEEN ValidFrom AND ValidTo AND SysID = 101 OPEN curs FETCH NEXT FROM curs INTO @SchemaID WHILE @@FETCH\_STATUS = 0 BEGIN /\*Do your commands for @SchemaID here\*/ /\*Get the next author.\*/ FETCH NEXT FROM curs INTO @SchemaID END CLOSE curs DEALLOCATE curs
### Apex SQL Refactor ApexSQL Refactor is a SQL Server Management Studio and Visual Studio free add-in, for format and refactor SQL code and objects. ApexSQL Refactor has 200+ formatting options and nearly 15 code refactors [Apex SQL Refactor Introduction](https://www.apexsql.com/Video/youtube/refactor/) ApexSQL Refactor can: - Qualify SQL Server object names, expand wild cards and locate and highlight unused variables and parameters - Encapsulate SQL code into procedures, replace one-to-many relationships, add surrogate keys, change procedure parameters - Update all dependent database objects for renaming or changing columns and parameters without breaking any dependencies - Format SQL code in the SSMS or Visual Studio query window, it can format SQL objects or external SQL scripts [More Information](https://knowledgebase.apexsql.com/apexsql-refactor-overview/) #### Install the Add-on The add-on can be found locally on Adriano. The following path can be used: ```YAML \\Adriano\FileServer\CDRack\SQL_Apex\Apex SQL Refactor\ApexSQLRefactor.exe ``` #### Configuring the signify Profile In order to allow all user using the refactor add-on a default in signify profile has been configured. After the installation has been completed the attached refactor profile, FormattingSettings.zip, must be downloaded and imported in SSMS using the following path: ```YAML ApexSQL|Apex SQL Refactor|Options|Import ``` Once the import has been completed, select the Signify profile under the profile drop down list and set the profile as active. The window can now be closed. To refactor a query using this tool press **ctrl+shift+alt+F** In order to replace \* in select \* from with the corresponding column names press **Ctrl+Shift+Alt+U** ### Apex SQL Search ApexSQL Search is a free SQL search add-in for SSMS and Visual Studio. It offers text search in SQL database objects and data, allows safe renaming of SQL objects, and graphical visualization of object interdependencies [Apex SQL Search Introduction](https://www.apexsql.com/Video/youtube/search/) With ApexSQL Search you can: - Search for text within database objects (including object names) using the Object search - Search for data stored in tables and views (even encrypted ones) using the Text search - Repeat previous searches in a single click using the Search history - Visualize (and print) all objects’ relationships using the Dependency viewer - Change the name and schema of tables, views, stored procedures, functions, columns, and parameters without breaking your databases with the Safe rename refactor - Visually edit SQL objects’ extended properties via the Extended property editor feature [More Information](https://knowledgebase.apexsql.com/apexsql-search-toc/) #### Install the Add-on The add-on can be found locally on Adriano. The following path can be used: ```YAML \\Adriano\FileServer\CDRack\SQL_Apex\Apex SQL Search\ApexSQLSearch.exe ```