Thursday, August 9, 2018

SQL table to HTML

http://www.sqlservercentral.com/scripts/TSQL/175511/?utm_source=SSC&utm_medium=pubemail

SQL table to HTML

By Eduardo Pivaral

Convert any table or select query to a html table format

SP: sp_TabletoHTML
Version: 1.1
AUTHOR: Eduardo Pivaral sqlguatemala.com
MIT License
This stored procedure converts a table or select query to a HTML table format, with some customization options.
I have taken as a base, a script Carlos Robles (dbamastery.com) provided me for a static table, so i modified it to accept any table and apply different or no styles, also you can output or not the column names to the table.

NOTES:


  • This SP works with dynamic queries, also data is not validated, so it is vulnerable to SQL injection attacks, so always validate your queries first.
  • Null values are not converted on this initial release, so before using it, remove null values from your data.
  • Some special datatypes like geography, timestamp, xml, image are not supported, if you try to use them, an error will raise, remove these columns before using it.
  • This tool is not designed to handle huge amounts of data, so, for massive information you can split them in various executions.

PARAMETERS:


  • @stTable: input table or SELECT query, a schema.object or SELECT query format
  • @RawTableStyle: OUTPUT variable, to use in another process or programatically
  • @includeColumnName: 0=does not include column names | 1=include column names (DEFAULT)
  • @TableStyle: 0=no style | 1=black borders (DEFAULT) | 2=grey style | 3=lightblue style | 4=zebra-striped table

SAMPLE EXECUTION:


Most basic usage, table name and all defaults to query window
EXEC sp_TabletoHTML @stTable = 'sys.dm_os_windows_info'
Output:
table output
SELECT QUERY, all defaults
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @RawTableStyle = @st OUTPUT
Output:
table output
Remove column name
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @includeColumnName = 0,
 @RawTableStyle = @st OUTPUT
Output:
table output
Gray style with columns
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @TableStyle = 2,
 @RawTableStyle = @st OUTPUT
Output:
table output
Lightblue with columns
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @TableStyle = 3,
 @RawTableStyle = @st OUTPUT
Output:
table output
zebra-striped table
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @TableStyle = 4,
 @RawTableStyle = @st OUTPUT
Output:
table output
Remove style and columns
SET @SQLSentence = 'SELECT name,state_desc ,create_date,collation_name FROM sys.databases'

EXEC sp_TabletoHTML @stTable = @SQLSentence,
 @TableStyle = 0,
 @includeColumnName = 0,
 @RawTableStyle = @st OUTPUT
Output:

table output

IF OBJECT_ID('dbo.sp_TabletoHTML') IS NULL
EXEC ('CREATE PROCEDURE dbo.sp_TabletoHTML AS SELECT 1;');
GO

ALTER PROCEDURE [dbo].[sp_TabletoHTML] 
@stTable AS NVARCHAR(max),
@RawTableStyle AS NVARCHAR(max) = '' OUTPUT,
@includeColumnName AS BIT = 1, 
@TableStyle AS TINYINT = 1 
AS
BEGIN
/*******************************************************************************
Convert any table or select query to a html <table> format
FROM: https://github.com/Epivaral/sql-table-to-html

SP: sp_TabletoHTML
Version: 1.1
AUTHOR: Eduardo Pivaral (www.sqlguatemala.com)
MIT License
This stored procedure converts a table or select query to a HTML table format, 
with some customization options.

I have taken as a base, a script Carlos Robles (http://dbamastery.com/) 
provided me for a static table, so i modified it to accept any table and apply different
or no styles, also you can output or not the column names to the table.

NOTES:
----------  
* This SP works with dynamic queries, also data is not validated,
so it is vulnerable to SQL injection attacks, so always validate your queries first.
* Null values are not converted on this initial release, so before using it,
remove null values from your data.
* Some special datatypes like geography, timestamp, xml, image are not supported,
if you try to use them, an error will raise, remove these columns before using it.
* This tool is not designed to handle huge amounts of data, so, for massive information
you can split them in various executions.
-----------

PARAMETERS:
-----------
@stTable: input table or SELECT query, a schema.object or SELECT query format
@RawTableStyle: OUTPUT variable, to use in another process or programatically
@includeColumnName:  0=does not include column names | 1=include column names (DEFAULT)
@TableStyle: 0=no style | 1=black borders (DEFAULT) | 2=grey style | 3=lightblue style | 4=zebra-striped table
-----------


SAMPLE EXECUTION:
-----------------
Most basic execution with all defaults:

EXEC sp_TabletoHTML @stTable = 'sys.dm_os_sys_info'

more execution examples at: https://github.com/Epivaral/sql-table-to-html
-----------------
*******************************************************************************/

SET NOCOUNT ON;
IF EXISTS (
SELECT *
FROM tempdb.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = '##rowstablePreHTML'
)
BEGIN
DROP TABLE ##rowstablePreHTML
END

/*** BASIC SQL Injection detection, always make your own validations before input any code */
IF (
(CHARINDEX('DELETE ', @stTable) > 0)
OR (CHARINDEX('INSERT ', @stTable) > 0)
OR (CHARINDEX('UPDATE ', @stTable) > 0)
OR (CHARINDEX('INTO ', @stTable) > 0)
OR (CHARINDEX('DROP ', @stTable) > 0)
OR (CHARINDEX('TRUNCATE ', @stTable) > 0)
OR (CHARINDEX('MERGE ', @stTable) > 0)
OR (CHARINDEX('EXEC ', @stTable) > 0)
OR (CHARINDEX('EXECUTE ', @stTable) > 0)
OR (CHARINDEX('--', @stTable) > 0)
OR (CHARINDEX(';', @stTable) > 0)
OR (CHARINDEX('XP_', @stTable) > 0)
OR (CHARINDEX('KILL ', @stTable) > 0)
)
BEGIN
THROW 50000,'Only Select statements or schema.object names are allowed as an input',1;
RETURN;
END
/********************************************************************************************/

/************** INTERNAL PARAMETERS **************/
DECLARE @ColumnST AS NVARCHAR(max) = ''
DECLARE @newSelect AS NVARCHAR(max) = ''
DECLARE @ColumnNamesHTML AS NVARCHAR(max) = ''
DECLARE @CSSTableStyle AS NVARCHAR(max) = ''
DECLARE @SelectStatement as NVARCHAR(max) = ''
DECLARE @STErrorMessage as NVARCHAR(max)=''
/************* END INTERNAL PARAMETERS *************/
IF(CHARINDEX('SELECT',@stTable)>0)
BEGIN
SET @SelectStatement = 'SELECT tbl1.* into ##rowstablePreHTML FROM (' + @stTable+') tbl1'
END
ELSE
BEGIN
SET @SelectStatement= 'SELECT tbl1.* into ##rowstablePreHTML FROM ' + @stTable + ' tbl1'
 
END
BEGIN TRY
EXEC sp_executesql @SelectStatement --Loading table contents on temp table
END TRY  
BEGIN CATCH
SET @STErrorMessage ='Syntax related issue with your input, use "<schema>.<table>" or "SELECT <columns> FROM <TABLE>" format. ERROR REPORTED: '+ERROR_MESSAGE();
THROW 50000, @STErrorMessage ,1;
RETURN;
END CATCH; 


SET @ColumnST = (
SELECT '[' + COLUMN_NAME + ']' AS 'TH'
FROM tempdb.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '##rowstablePreHTML'
FOR XML raw('TR'),
elements
) -- Obtain columns for the table 

-- performing cleanup task for columns
SET @ColumnST = REPLACE(@ColumnST, '<TR>', '')
SET @ColumnST = REPLACE(@ColumnST, '</TR>', '')

SET @ColumnNamesHTML = '<TR>' + @ColumnST + '</TR>' --Obtaining column names, we will use this later to append to the table

-- Removing [] we put before on the columns
SET @ColumnNamesHTML = REPLACE(@ColumnNamesHTML, '[', '')
SET @ColumnNamesHTML = REPLACE(@ColumnNamesHTML, ']', '')

-- we continue cleanup tasks for columns before creating or dynamic Select
SET @ColumnST = REPLACE(@ColumnST, '<TH>', '')
SET @ColumnST = REPLACE(@ColumnST, '</TH>', 'as TD,') --creating all column names with the same name 
SET @ColumnST = LEFT(@ColumnST, LEN(@ColumnST) - 1) -- Removing last comma

-- generating select statement on an HTML friendly format
SET @newSelect = 'SELECT @RawTableStyleOUT =(SELECT ' + isnull(@ColumnST, '') + ' FROM ##rowstablePreHTML For XML RAW(''TR''), ELEMENTS)'

EXEC sp_executesql @newSelect,
N' @RawTableStyleOUT as nvarchar(max) OUTPUT',
@RawTableStyleOUT = @RawTableStyle OUTPUT

IF (@TableStyle = 0) -- no Style
BEGIN
SET @CSSTableStyle = '' 
END

IF (@TableStyle = 1) -- black borders
BEGIN
SET @CSSTableStyle = '<style type="text/css">
table, th, td {border: 1px solid; border-collapse: collapse;}
</style>'
END

IF (@TableStyle = 2) -- Grey style
BEGIN
SET @CSSTableStyle = '<style type="text/css">
table, td, tr {border: 1px solid #dddddd; padding: 3px; color: #555555; border-collapse: collapse;}
th {background-color: #dddddd;}
</style>'
END

IF (@TableStyle = 3) -- lightblue borders
BEGIN
SET @CSSTableStyle = '<style type="text/css">
table, td, tr {border: 1px solid #DCDCDC; padding: 2px; color: #808080; border-collapse: collapse;}
th {border: 1px solid #DCDCDC;background-color: #1E90FF;color:#FFFFFF;}
</style>'
END

IF (@TableStyle = 4) -- zebra-striped table
BEGIN
SET @CSSTableStyle = '<style type="text/css">   
table, td, tr {border: 1px solid #dddddd; padding: 3px; color: #555555; border-collapse: collapse;}   
th {background-color: #CCCCCC;}  
tr:nth-child(even) {background-color: #F7F7F7} 
</style>'
END

IF(@includeColumnName =1) --IF Column names must be included
BEGIN
SET @RawTableStyle = @ColumnNamesHTML + @RawTableStyle
END
SET @RawTableStyle = @CSSTableStyle + '<TABLE>' + isnull(@RawTableStyle,'') + '</TABLE>'

SELECT @RawTableStyle

END
GO

The Top Five Things That DBAs Need to Monitor

https://www.red-gate.com/simple-talk/blogs/the-top-five-things/

Being a database administrator is much more than knowing how to install SQL Server and set up a database. One of the most important responsibilities is being proactive by monitoring the instances in their care. But, what should be monitored? Here are the top five things to monitor when you are a SQL Server DBA:
#5 Job outcomes: Great DBAs automate everything they can and use SQL Server Agent or some other job scheduler to run the scripts. They understand what the jobs do and the consequences of a job failure or long running job. They also have every job documented so that they can take a day off once in a while!
#4 File growth: Over time, database files can run out of free space as can the volumes where these files live. Transactions must wait while database files grow. Applications can grind to a halt if there is no more space in the files or space runs out on the volume. Nobody wants that!
#3 Backups: There are exceptions, but just about every database should be backed up on a regular basis, including frequent transaction log backups. Unless you have a job in place to back up EVERY database on an instance by default, it’s easy to miss adding new databases. By the way, make sure you have a process in place to test backup files as well.
#2 Security: Are you keeping track of how many accounts are in the sysadmin group? How about failed logins? Keeping a company’s databases secure is the most important task a DBA has, and monitoring can help you spot unusual activity.
#1 Performance: When was the last time someone called you to say that their application was running fast? (I didn’t think so!) Taking baselines, watching resource utilization (CPU, memory, I/O) changes over time, determining the top 10 or so worst performing queries so you can tune them…There is so much to do here, but this is your chance to shine!
Now that you have an idea about what to monitor, how do you do it? The best way is by using a monitoring tool like Redgate’s SQL Monitor. It has best practices built right in, but it’s also highly configurable if you need to deviate a bit from those best practices. The best part is that it’s so easy to use. It can support hybrid environments, large estates, Availability Groups, and more! Take it for a spin on Redgate’s own servers.

weekly calendar of sales for 2016. She makes it clear that she wants to see a list of all the weeks in the year, whether there were any sales in that week or not

http://www.sqlservercentral.com/articles/T-SQL/173370/?utm_source=SSC&utm_medium=pubemail

Using a CTE as a Tally Table

By Adam Aspin
This is the sixth article in a short series of SQL Server query challenges to test and expand your SQL Server querying skills. While none of these short articles is of overwhelming complexity, they will hopefully either teach you something new or help you to reactivate potentially dormant SQL skills in preparation for your next real-world challenge. You can see the rest of the articles on the Query Answers with SQL Server page.
In this article we will once again imagine that you are working for a small classic car retailer called Prestige Cars Ltd, using the data that is in the company database.

The Challenge

The CEO has just had another idea; you can tell by the smile on her face as she walks over to your desk. Hiding your trepidation, you listen as she tells you that she needs a weekly calendar of sales for 2016. She makes it clear that she wants to see a list of all the weeks in the year, whether there were any sales in that week or not. Your challenge is to come up with the SQL to satisfy her request. Here is one possible solution:
;
WITH Tally_CTE
AS
(
SELECT     TOP 52 ROW_NUMBER() OVER (ORDER BY StockCode) AS Num
FROM       Data.Stock
)
SELECT           Num, SalesForTheWeek
FROM             Tally_CTE CTE
LEFT OUTER JOIN  
                 (
                 SELECT         SUM(TotalSalePrice) AS SalesForTheWeek
                               ,DatePart(wk, SaleDate) AS WeekNo
                 FROM          Data.Sales
                 WHERE         YEAR(SaleDate) = 2016
                 GROUP BY      DatePart(wk, SaleDate)
                 ) SLS
                 ON CTE.Num = SLS.WeekNo
Running this SQL produces output like that shown in Figure 1.
Figure 1. Displaying missing data using a sequence list

How It Works

Delivering data when the data exists is rarely an issue; however, you may need to apply slightly different querying techniques if you need to show “missing” data. By this, we mean that SQL does not naturally create complete lists of dates, or date elements such as weeks, where there is no corresponding data in a database.
We are presuming, here, that the Sales table (which, as its name indicates, contains itemized sales details including the sale date) might not contain a sale on every day of the year.
To understand this problem more clearly, run the SQL from the preceding snippet that returns the total sales per week for 2016, which is contained in the derived table with the alias SLS. The output from the derived table looks like that shown in Figure 2.
Figure 2. The source data with missing values
Although the figures are accurate, the data contains holes since there are no sales for certain weeks. Since these holes could be precisely the data that you want to focus on, it is important to return a full list of weeks—whether they contain data or not.
Forcing SQL Server to return a complete sequence (whether it is dates, weeks, or any other series of information) requires you to extend the SQL with a list that contains an unbroken and consecutive list of all the elements that you need to view. You can then use this list as the basis for a query that adds the aggregated output that you require. 
A sequence like this is often called a tally table or a numbers list. What you have done in this SQL is

First:

Created a CTE (Common Table Expression) that contains a numbers list.

Second:

Joined the CTE to a query (the derived subquery in this example) that calculates the sales per week.
Let’s begin by looking at the numbers table. Although we call this a table, it is really a dataset generated by a CTE. If you run the code inside the CTE named Tally_CTE, you see the output in Figure 3.
Figure 3. A sequence list or tally table
As you can see, this CTE simply returns a sequence of numbers. You obtain this sequence by

First:

Choosing a table that contains more records than you need in the numbers table (the CTE output).

Then:

Selecting the first n records from this table that correspond to the number of items in the sequence that you require. In this example, there are 52 weeks in the year, so you use TOP 52 to limit the number of elements in the tally table.

Finally:

Since you are not interested in the actual data that the source table (Stock) contains, but only in the number of records, you define a ROW_NUMBER() function (ordered by any field in the table) to provide a sequence of numbers.
The CTE at the start of the SQL serves only to provide a sequential list that provides a row for each week in the year.
Once you have the tally table set up, join this to the derived table that returns the actual data for each week of sales. Because you have extracted the week number from the SaleDate field using the DATEPART() function, you can join the week number for each week of sales to the corresponding record in the tally table. Defining the join as a LEFT OUTER join from the tally table (the CTE) to the derived query ensures that every record from the CTE is displayed, whether or not any corresponding data is in the derived query.
The result is the output from Figure 1, shown previously, that shows all the weeks in 2016 with the sales figures, even if there are no sales for a specific week. 

Note:

If you use a single table as the basis for the tally table, it must contain at least as many records as you need for the sequential list. The next section explains a technique you can use to guarantee enough rows if you are worried that a single source table will not contain enough records.
That is it – you have seen a simple example of how to displaying records for missing data. Keep watching SQL Server Central.com ready for the next article in this series.
This article is adapted from the book “Query Answers with SQL Server Volume II: In-Depth Querying” by Adam and Karine Aspin. Available as both a paperback and an eBook from all good resellers including Amazon, Kobo and iBooks, as well as all good bookstores.
The sample data is available either in the accompanying material for this article, or on the Tetras Publishing website at: www.tetraspublishing.com/sqlserver.

The Series

There are a number of articles in this series. You can see them all on the Query Answers page.
 

Resources:

SQLQueriesSampleData.zip

Tuesday, August 7, 2018

create password randomly in sql server


https://blog.sqlauthority.com/2018/08/02/sql-server-how-to-generate-random-password-enhanced-version/



CREATE PROCEDURE GenerateRandomPwd1 (@length int = 20,
@allowAtoZ BIT = 1,
@allow0to9 BIT = 1,
@allowSpecials1 BIT = 1,
@allowSpecials2 BIT = 1,
@avoidAmbiguousCharacters BIT = 1) AS
BEGIN
DECLARE @pwd VARCHAR(512) = ''
--use master.dbo.spt_values as a pseudo tally(numbers) table
SELECT TOP (@length) @pwd += CHAR(fn.rnd)
FROM master.dbo.spt_values sv
CROSS APPLY (
-- (max - min) + min
SELECT [rnd] = (ABS(CHECKSUM(NEWID())) % (123 - 33)) + 33
) fn
WHERE (@avoidAmbiguousCharacters = 0 OR fn.rnd NOT IN (73, 108, 124, 79, 48, 49)) --capital i, lowercase l, vertical bar | capital o, the number(s) 0, 1
AND (
(@allowAtoZ = 1 AND ((fn.rnd &gt;= 65 AND fn.rnd &lt;= 90) OR (fn.rnd &gt;= 97 AND fn.rnd &lt;= 122)))
OR (@allow0to9 = 1 AND (fn.rnd &gt;= 48 AND fn.rnd &lt;= 57))
OR (@allowSpecials1 = 1 AND (fn.rnd &gt;= 33 AND fn.rnd &lt;= 47))
OR (@allowSpecials2 = 1 AND (fn.rnd &gt;= 58 AND fn.rnd &lt;= 64))
)
SELECT [Password] = @pwd,
[@allowAtoZ] = @allowAtoZ,
[@allow0to9] = @allow0to9,
[@allowSpecials1] = @allowSpecials1,
[@allowSpecials2] = @allowSpecials2,
[@avoidAmbiguousCharacters] = @avoidAmbiguousCharacters
END
GO
Now let us run the same stored procedure with few parameters.
1
2
3
4
EXEC GenerateRandomPwd1 @length = 20, @avoidAmbiguousCharacters = 0
EXEC GenerateRandomPwd1 @length = 20, @allow0to9 = 0, @allowSpecials1 = 0, @allowSpecials2 = 0, @avoidAmbiguousCharacters = 0
EXEC GenerateRandomPwd1 @length = 20, @allow0to9 = 0, @allowSpecials1 = 0, @allowSpecials2 = 0, @avoidAmbiguousCharacters = 1
EXEC GenerateRandomPwd1 @length = 20, @allowAtoZ = 0, @allow0to9 = 0, @allowSpecials1 = 1, @allowSpecials2 = 1