Skip to content

Commit 4d56599

Browse files
fresh initialize
0 parents  commit 4d56599

30 files changed

+2041
-0
lines changed

README.md

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Microsoft SQL Server Scripts
2+
3+
This repository contains a collection of my SQL scripts saved in one convenient place. Feel free to rummage around.
4+
5+
In the **Tools** folder, you'll find an assortment of useful scripts, including those for generating a well-structured calendar table, conducting data profiling, and offering quick fixes for common data issues I face on a routine basis. These scripts are a little more involved and I include instructions on their usage.
6+
7+
The **Scripts** folder serves as a repository for all the scripts I employ to query system tables or provide some quick solutions to common problems. These scripts are pretty straight forward, just follow the code comments at the top of each script.
8+
9+
:keyboard:      All SQL is written in Microsoft SQL Server T-SQL, unless otherwise noted.
10+
11+
:question:      If you have any questions, please feel free to create a GitHub discussion. I am always happy to help out and explain different solutions.
12+
13+
:mailbox:      If you find any inaccuracies, misspellings, bugs, dead links, etc., please report an issue! No detail is too small, and I appreciate all the help.
14+
15+
:smile:      Happy coding!
16+
17+
I hope you find this repository useful and informative, and I welcome any new puzzles or tips and tricks you may have. I also have a WordPress site where you can find my data analytics projects, Python puzzles, and blog.
18+
19+
**https://advancedsqlpuzzles.com**

Scripts/AsciiValues.sql

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
Returns the ASCII values of a string
3+
4+
This script loops through a string and displays
5+
all the ASCII characters in the string.
6+
*/
7+
DECLARE @vMyString VARCHAR(100) = 'Hello World';
8+
DECLARE @vLength INTEGER = LEN(@vMyString);
9+
DECLARE @vPosition INTEGER = 0;
10+
DECLARE @vAscii VARCHAR(MAX) = '';
11+
12+
--Begin Loop
13+
WHILE @vLength >= @vPosition
14+
BEGIN
15+
SELECT @vAscii = @vAscii + CONCAT(ASCII(SUBSTRING(@vMyString,@vPosition,1)),',');
16+
SELECT @vPosition = @vPosition + 1;
17+
END;
18+
19+
--Removes beginning and ending commas
20+
SET @vAscii = SUBSTRING(@vAscii,2,LEN(@vAscii)-2);
21+
22+
SELECT @vAscii AS AsciiCodes;

Scripts/CursorExample.sql

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
Cursor Example
3+
4+
A quick example of a Microsoft SQL Server cursor usage.
5+
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql?view=sql-server-ver16
6+
*/
7+
8+
DECLARE @vMyVariable VARCHAR(100);
9+
DECLARE test_cursor CURSOR FOR (SELECT 'Hello World' UNION SELECT 'Goodbye World');
10+
11+
OPEN test_cursor;
12+
FETCH NEXT FROM test_cursor INTO @vMyVariable;
13+
WHILE @@FETCH_STATUS = 0
14+
BEGIN
15+
PRINT(CONCAT('The value is ', @vMyVariable));
16+
FETCH NEXT FROM test_cursor INTO @vMyVariable;
17+
END
18+
CLOSE test_cursor;
19+
DEALLOCATE test_cursor;

Scripts/DropDatabase.sql

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/*
2+
Drop Database
3+
4+
Script template for dropping a database in Microsoft SQL Server.
5+
https://learn.microsoft.com/en-us/sql/t-sql/statements/drop-database-transact-sql?view=sql-server-ver16
6+
*/
7+
USE MASTER;
8+
GO
9+
ALTER DATABASE <name> SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
10+
DROP DATABASE <name>;

Scripts/MissingIndexes.sql

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Missing Indexes
3+
4+
The following script finds missing indexes in Microsoft SQL Server.
5+
6+
The tables used are:
7+
sys.dm_db_missing_index_groups
8+
sys.dm_db_missing_index_group_stats
9+
sys.dm_db_missing_index_details
10+
*/
11+
SELECT
12+
GETDATE() AS runtime
13+
,@@Servername
14+
,REPLACE(REPLACE(mid.statement,']',''),'[','') AS tablename
15+
,migs.avg_total_user_cost
16+
,migs.avg_user_impact
17+
,migs.user_seeks
18+
,migs.user_scans
19+
20+
--Pulled from the internet.
21+
,CONVERT (DECIMAL (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS improvement_measure
22+
----------------------------
23+
--Index creation syntax
24+
,'CREATE INDEX missing_index_' + 'INDEX_NAME ON ' + mid.statement + ' (' + ISNULL (mid.equality_columns,'') +
25+
CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL
26+
THEN ','
27+
ELSE ''
28+
END + ISNULL (mid.inequality_columns, '') + ')' + ISNULL (' INCLUDE (' + mid.included_columns + ')', '')
29+
AS create_index_statement
30+
----------------------------
31+
,mid.database_id
32+
,mid.[object_id]
33+
FROM sys.dm_db_missing_index_groups AS mig INNER JOIN
34+
sys.dm_db_missing_index_group_stats AS migs ON migs.group_handle = mig.index_group_handle INNER JOIN
35+
sys.dm_db_missing_index_details AS mid ON mig.index_handle = mid.index_handle
36+
WHERE 1=1
37+
AND mid.statement NOT LIKE '%msdb%'
38+
ORDER BY
39+
user_seeks desc,
40+
migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC;
41+
--EXEC sp_helptext 'schecma.name'

Scripts/RandomNumbers.sql

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Random Numbers
3+
4+
The following script creates a table (#RandomNumbers) of random numbers between 1 and 10
5+
using the function ABS(CHECKSUM(NEWID()) % 10).
6+
7+
The loop below produces 10,000 random numbers ranging from 1 to 10 and subsequently displays
8+
the percentage distribution of these numbers to illustrate their randomness.
9+
*/
10+
DROP TABLE IF EXISTS #RandomNumbers;
11+
GO
12+
CREATE TABLE #RandomNumbers
13+
(
14+
MyRandomNumber INTEGER NOT NULL
15+
);
16+
GO
17+
DECLARE @i INTEGER = 1;
18+
DECLARE @loops INTEGER = 100000;
19+
WHILE @i <= @loops
20+
BEGIN
21+
INSERT INTO #RandomNumbers SELECT ABS(CHECKSUM(NEWID()) % 10) + 1;
22+
SET @i = @i + 1;
23+
END
24+
GO
25+
----------------------------------------------------------------
26+
----------------------------------------------------------------
27+
WITH cte_Total AS
28+
(
29+
SELECT COUNT(MyRandomNumber) AS MyTotal FROM #RandomNumbers
30+
),
31+
cte_Count AS
32+
(
33+
SELECT MyRandomNumber, COUNT(*) AS MyCount
34+
FROM #RandomNumbers a CROSS JOIN
35+
cte_Total b
36+
GROUP BY MyRandomNumber
37+
)
38+
SELECT MyRandomNumber,
39+
MyCount,
40+
MyCount / CAST(MyTotal AS NUMERIC(10,2))
41+
FROM cte_Count a CROSS JOIN
42+
cte_Total b;
43+
GO

Scripts/SQLServerAgentJobSteps.sql

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
SQL Server Agent Job Steps
3+
4+
This SQL script prints out Microsoft SQL Server Agent job steps.
5+
6+
dbo.sysjobsstep
7+
Contains the information for each step in a job to be
8+
executed by SQL Server Agent. This table is stored in the msdb database.
9+
10+
dbo.sysjobs
11+
Stores the information for each scheduled job to be executed by SQL Server Agent.
12+
This table is stored in the msdb database.
13+
*/
14+
15+
SELECT @@SERVERNAME AS ServerName,
16+
s.step_id AS 'StepID',
17+
j.[name] AS 'SQLAgentJobName',
18+
s.[database_name] AS 'DBName',
19+
s.command AS 'Command'
20+
FROM msdb.dbo.sysjobsteps s INNER JOIN
21+
msdb.dbo.sysjobs AS j ON s.job_id = j.job_id
22+
WHERE 1=1
23+
AND s.command LIKE '%example_command%';

Scripts/Sp_HelpText.sql

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/*
2+
sp_helptext Example.
3+
4+
sp_helptext displays the definition that is used to create an object in multiple rows.
5+
Each row contains 255 characters of the Transact-SQL definition.
6+
The definition resides in the definition column in the sys.sql_modules catalog view.
7+
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-helptext-transact-sql?view=sql-server-ver16
8+
*/
9+
10+
DECLARE @vTableVariable TABLE(SpText VARCHAR(MAX));
11+
DECLARE @vStoredProcedureName VARCHAR(255) = 'spTest';
12+
INSERT INTO @vTableVariable
13+
EXEC sp_helptext @vStoredProcedureName;
14+
SELECT * FROM @vTableVariable;
15+

Scripts/StoredProcedureDefinition.sql

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/*
2+
Stored Procedure Definition
3+
4+
The following script prints out the body of a stored procedure.
5+
See also sp_helptext.
6+
*/
7+
8+
SELECT o.name, o.type_desc, o.create_date, o.modify_date, m.*
9+
FROM sys.sql_modules m LEFT OUTER JOIN
10+
sys.all_objects o on m.object_id = o.object_id
11+
WHERE m.definition like '%myText%';

Scripts/TableColumnNames.sql

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Table Column Names
3+
4+
This script searches for schemas, tables, columns, and data types within a database.
5+
Add the predicate logic you are searching for.
6+
*/
7+
8+
--sys.schemas
9+
--sys.tables
10+
SELECT @@SERVERNAME as ServerName,
11+
s.name AS SchemaName,
12+
t.name AS TableName
13+
FROM sys.schemas s LEFT OUTER JOIN
14+
sys.tables t ON s.schema_id = t.schema_id
15+
WHERE 1=1
16+
ORDER BY 1,2,3;
17+
18+
--sys.schemas
19+
--sys.tables
20+
--sys.columns
21+
--sys.types
22+
SELECT @@SERVERNAME as ServerName,
23+
s.name AS SchemaName,
24+
t.name AS TableName,
25+
c.name AS ColumnName,
26+
ty.name as DataType,
27+
CONCAT('SELECT * FROM ',s.name,'.',t.name,';') as QuickQuery
28+
FROM sys.schemas s LEFT OUTER JOIN
29+
sys.tables t ON s.schema_id = t.schema_id INNER JOIN
30+
sys.columns c ON t.object_id = c.object_id INNER JOIN
31+
sys.types ty ON ty.user_type_id = c.user_type_id
32+
WHERE 1=1
33+
ORDER BY 1,2,3,4;

Scripts/readme.md

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
## Overview
2+
Welcome to this GitHub repository, my go-to collection of SQL Server scripts that I have collected and saved to make life easier.
3+
4+
## How to Use
5+
Feel free to rummage around. I'm constantly adding and reorganizing this site, so if you cannot find anything, let me know, and I would be happy to help.
6+
7+
## Notes
8+
:keyboard:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;All SQL is written in Microsoft SQL Server T-SQL, unless otherwise noted.
9+
10+
:question:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If you have any questions, please feel free to create a GitHub discussion. I am always happy to help out and explain different solutions.
11+
12+
:mailbox:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If you find any inaccuracies, misspellings, bugs, dead links, etc., please report an issue! No detail is too small, and I appreciate all the help.
13+
14+
:smile:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Happy coding!
15+
16+
I hope you find this repository useful and informative, and I welcome any new puzzles or tips and tricks you may have. I also have a WordPress site where you can find my data analytics projects, Python puzzles, and blog.
17+
18+
**https://advancedsqlpuzzles.com**
19+
20+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*-----------------------------------------------------------------------
2+
Scott Peters
3+
Creating a Calendar Table
4+
https://advancedsqlpuzzles.com
5+
Last Updated: 01/11/2023
6+
Microsoft SQL Server T-SQL
7+
8+
This script shows an example usage of the function FnReturnCalendarTable.
9+
10+
*/-----------------------------------------------------------------------
11+
12+
SET NOCOUNT ON;
13+
DROP TABLE IF EXISTS CalendarDaysTemp;
14+
GO
15+
16+
--Create a temporary calendar table
17+
CREATE TABLE CalendarDaysTemp
18+
(
19+
DateKey INT NOT NULL PRIMARY KEY,
20+
CalendarDate DATE NOT NULL
21+
);
22+
GO
23+
24+
-----------------------------------------------------
25+
-- Populate the CalendarTable
26+
DECLARE @vStartDate DATE = '2020-01-01';
27+
WHILE @vStartDate <> '2021-01-01'
28+
BEGIN
29+
INSERT INTO CalendarDaysTemp(DateKey, CalendarDate) VALUES
30+
(
31+
CONVERT(INT,CONVERT(VARCHAR, @vStartDate, 112)),
32+
@vStartDate
33+
);
34+
35+
SET @vStartDate = DATEADD(DAY,1,@vStartDate);
36+
END;
37+
38+
-----------------------------------------------------
39+
-----------------------------------------------------
40+
41+
--Basic usage with CROSS APPLY
42+
SELECT ct.*
43+
FROM CalendarDaysTemp cd CROSS APPLY
44+
FnReturnCalendarTable(cd.CalendarDate) ct
45+
WHERE cd.DateKey = ct.DateKey;
46+
GO
47+
48+
--Create a view
49+
CREATE OR ALTER VIEW VwCalendarTable AS
50+
SELECT ct.*
51+
FROM CalendarDaysTemp cd CROSS APPLY
52+
FnReturnCalendarTable(cd.CalendarDate) ct
53+
WHERE cd.DateKey = ct.DateKey;
54+
GO
55+
56+
57+
SELECT top 1 * FROM VwCalendarTable;

0 commit comments

Comments
 (0)