Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, September 16, 2019

Free Databases and Data Visualisations course for kids Week 8 update

Today I conducted a SQL test for kids to gauge their understanding of what I have taught them so far in SQL.

Altogether 10 kids participated in the SQL test.
This test is online and if any of you want to try the test you can try

The link is below:
SQL Test 

A few photos from the night below




Tuesday, September 10, 2019

Free Databases and Data Visualisations course for kids Week 7 update

Had a great time this week with kids who attended the SQL course yesterday. #sqlfamily #microsoftnz #mvpbuzz

This week they learnt how to import data from a csv file.  After they imported the file, I have asked them to view what they have imported and most of the kids started writing the select queries for all my questions. I again had a short recap of the last week's session covering update, delete and basic SQL functions.

In the next session, I will be organising a test to understand how much they have learnt.








Tuesday, September 03, 2019

Free Databases and Data Visualisations course for kids Week 6 update

Databases and Data Visualisations course for kids aged between 9 to 14 years week 6 update.

Had a great time this week with kids attending the SQL course. #sqlfamily #microsoftnz #mvpbuzz

I had a short recap of the last week's session covering update, delete and basic SQL functions.

This week they learnt how to import data from a csv file.  After they imported the file, I have asked them to view what they have imported and most of the kids started writing the select queries for all my questions.

In the next session I am planning to cover table joins to them. Hopefully this will be the last session on databases after which I will be organising a test

I am looking forward for the session on next Monday.




Wednesday, August 28, 2019

Free Databases and Data Visualisations course for kids Week 5 update

Databases and Data Visualisations course for kids aged between 9 to 14 years week 5 update. Had a great time on Monday with 10 kids and 2 parents attending the SQL course. #sqlfamily #microsoftnz 

There was no class last week as I was away in Melbourne at the #powerplatformsummit.

So there was almost a 2 week gap so I revised all that they have learnt so far in the last 4 weeks by asking them a lot of questions.  Most of the questions some of the kids answered them right but the revision helped them to understand a bit more.

I was pleased to see most of the kids eagerly answering my questions. I felt that now all the kids are able to genuinely understand what I am trying to teach them.

This week they learnt some of the basic SQL functions like Min, Max, Count, AVG, SUM.  String functions like Left and Right.

In the next session I am planning to cover the importing of data from a csv and also will try and explain joins to them.

I am looking forward for the session on next Monday.






Tuesday, August 13, 2019

Free Databases and Data Visualisations course for kids Week 4 update

Databases and Data Visualisations course for kids aged between 9 to 14 years week 4 update. It was another full house on Monday with 12 kids and 4 parents attending the course. #sqlfamily #microsoftnz  


The first 45 minutes were spent in solving issues with questions like --
- 'I created a table but I cannot see it'
- 'Why is my insert statement not working ?'
- 'I have inserted a lot of duplicate records.  How do I delete them ?'
- 'I am getting a syntax error'

After this, when I did the recap of what happened last week, I was pleased to see most of the kids eagerly answering my questions. I felt that now all the kids are able to genuinely understand what I am trying to teach them.

The agenda for this week was to explain the update and delete statements.  The Like and In operators in the where clause.  Some of the basic SQL functions like Min, Max, Count, AVG, SUM.  String functions like Left, Right and Substring.

It is interesting to see how some of the kids think.  One of them asked what if we accidentally deleted all records ?  Is there an undo?

As usual I felt very happy to see the enthusiasm in these kids. I am looking forward for the session on next Monday.




Tuesday, August 06, 2019

Free Databases and Data Visualisations course for kids Week 3

Free Databases and Data Visualisations course for kids Week 3
Databases and Data Visualisations course for kids aged between 9 to 14 years week 3 update. It was a full house yesterday with 15 kids and 5 parents attending the course. #sqlfamily #microsoftnz

During my recap of what happened last week, most of the kids wanted to answer all of my questions.  For the homework that I have given, Imost of them completed the creation of the tables.  But everyone forgot to create the foreign keys.

There were only 2 challenges faced by the kids when they were doing their home work. First was when they had a space in the database or table name. Second was the table was not created in the new database they created.

The agenda for week 3 was to show them how to insert data into the tables and view the data.  I could just cover select statement and basic where clause and the time was up.

I feel very happy to see the enthusiasm in all of these kids. I am looking forward for the session on next Monday.

Below are few photos from the session.






Tuesday, July 30, 2019

Free #Databases and Data Visualisations course for kids aged between 9 to 14 years week 2 update

It was good to see all the kids come back to hear all about databases for the 2nd week.  There were a few new enrolments.
So first I started off with a Recap of last week, to help the 3 new kids understand the database concepts and also to test the knowledge that all the others have gained. It was good to see that they remembered most of the concepts except for the redundancy part.

The agenda for week 2 was to show them how they could access SSMS and create a database and a table.  Most of them had hands on experience creating a database named schools and a table named school.

I also wanted to cover how to insert data in this week but ran out of time so will do that next week.

I have also given them some homework to ensure that they practice what was learnt in the past 2 sessions.

I am looking forward for the session on next Monday.  . #sqlfamily #microsoftnz #mvpbuzz




Tuesday, July 23, 2019

Databases and Data Visualisations Course for kids Season 2 Week 1

Databases and Data Visualisations Course for kids Season 2 Week 1
I have started the second leg of Databases and Data Visualisations course for kids aged between 10 to 14 years yesterday.

This time I have asked the kids to fill out a survey to understand their current level of knowledge regarding what data is and what visualisation is. I also asked what they want to get out of this course.

The answers ranged from "understanding the basics of data" to "Learn about the basics of data visualization and what I can do about it in the future "

The best answer I liked was "I want to learn more about databases online. I also want to learn a little bit of coding since that is definitely not my best factor. I want to learnt things that I didn't know before to extend my thinking and become more all-rounder."

From the survey, I was confident that the kids already knew what data means and they could easily give some examples.

To explain about Relational Databases and Normalisation, I have asked each one of them to type in some information about their student ids names, classes, their emails, teachers and teacher's emails and schools.

This activity proved to be useful to make them understand the concept of redundancy and the disadvantages that arise out of it.  Then it was easy for me to explain the concept of Normalisation.

I have given them home work of installing SQL Server on their laptops.

I am looking forward for the session of Creating databases and tables using SQL Server next Monday.





Tuesday, June 27, 2017

Rerunning all subscriptions for a particular report that have failed.

Today I had a situation where a few of the subscriptions for a particular report have failed. I needed a script to run only these subscriptions manually.  Basically I am extending my previous blog post to achieve this by passing the result of my query into a cursor and executing the subscriptions using the sp_start_job stored procedure as follows:

Do not forget to deallocate the cursor.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use ReportServer
go
DECLARE @ScheduledReportName varchar(200)
DECLARE @JobID uniqueidentifier
DECLARE @LastRunTime datetime
Declare @JobStatus Varchar(100)
--------------------------------------------------------
DECLARE @RunAllReport CURSOR
SET @RunAllReport = CURSOR FAST_FORWARD
FOR
SELECT 
CAT.[Name] AS RptName
, res.ScheduleID AS JobID
, sub.LastRuntime
, LastStatus
FROM
dbo.Catalog AS cat
INNER JOIN dbo.Subscriptions AS sub
ON CAT.ItemID = sub.Report_OID
INNER JOIN dbo.ReportSchedule AS res
ON CAT.ItemID = res.ReportID
AND sub.SubscriptionID = res.SubscriptionID
INNER JOIN msdb.dbo.sysjobs AS job
ON CAST(res.ScheduleID AS VARCHAR(36)) = job.[name]
INNER JOIN msdb.dbo.sysjobschedules AS sch
ON job.job_id = sch.job_id
INNER JOIN dbo.Users U
ON U.UserID = sub.OwnerID
where res.ReportID ='3AA8BDD0456' 
AND  LastRunTime > GETDATE() - 1 AND LastStatus not like 'Mail sent%' AND LastStatus not like '%has been saved to%' AND LastStatus not like '%0 errors%' --AND LastStatus not like 'Pending%' 

OPEN @RunAllReport
FETCH NEXT FROM @RunAllReport
INTO @ScheduledReportName,@JobID,@LastRunTime,@JobStatus
WHILE @@FETCH_STATUS = 0
BEGIN
Print @ScheduledReportName --&' ' & @JobID
EXEC msdb.dbo.sp_start_job @job_name =@JobID
FETCH NEXT FROM @RunAllReport
INTO @ScheduledReportName,@JobID,@LastRunTime,@JobStatus
END
CLOSE @RunAllReport
DEALLOCATE @RunAllReport 

Thursday, June 22, 2017

Rerunning a SSRS subscription report

Yesterday I had a situation where  a couple of SSRS reports failed due to a network upgrade.

The SSRS report was not able to access the SQL server that was being used in the stored procedure.

So I had to rerun the report subscription manually.

To re-run the SSRS report subsciption I followed two steps.

Step 1:

I have used the below query to identify the job id of the failed reports.


SELECT
     S.ScheduleID AS SQLAgent_Job_Name, Sub.LastStatus, sub.LastRunTime, LastRunStatus
     ,SUB.Description AS Sub_Desc
     ,SUB.DeliveryExtension AS Sub_Del_Extension
     ,C.Name AS ReportName
     ,C.Path AS ReportPath

FROM ReportSchedule RS
     INNER JOIN Schedule S ON (RS.ScheduleID = S.ScheduleID)
     INNER JOIN Subscriptions SUB ON (RS.SubscriptionID = SUB.SubscriptionID)
     INNER JOIN [Catalog] C ON (RS.ReportID = C.ItemID AND SUB.Report_OID = C.ItemID)
WHERE
sub.LastRunTime > GETDATE() - 1 and  C.Name LIKE 'Reportname' 


Step 2:

I have copied the scheduleid and used a filter in the Jobs of the SSRS server as shown below.


Then Right click the Job and click 'Start Job at Step'

There are several other practices to achieve the same result.but I find that this is easier to follow.


Monday, June 12, 2017

Find the stored procedures and agents that use Linked Server

Today I had a scenario where I had to identify all the stored procedures and agents that used a particular Linked Server.  We are thinking of getting rid of these multiple  Linked Servers and combining them into one server.

So I have used the sys.sql_modules table to find out what stored procedures are using these linked servers.

The code I have written is as follows.

SELECT OBJECT_NAME(object_id) object ,  *
      FROM sys.sql_modules
      WHERE
Definition LIKE '%linkedsrv1%'
 OR
Definition Like '%linkedsrv2%'
 OR
 Definition Like '%linkedsrv3%'
      AND OBJECTPROPERTY(object_id, 'IsProcedure') = 1 ;


I have also used the sysjobsteps and sysjobs tables from msdb database to find out what jobs are using these Linked Servers,

The code I have written is as follows:

  SELECT j.name AS JobName,js.command
      FROM msdb.dbo.sysjobsteps jsteps
         INNER JOIN msdb.dbo.sysjobs jobs
            ON jobs.job_id = jsteps.job_id
      WHERE
 jsteps.command LIKE   '%linkedsrv1%'
 OR
jssteps.command Like  '%linkedsrv2%'
 OR
 jsteps.command Like  '%linkedsrv3%'


Next question that I am pondering is if we consolidate these servers into one server, what are the considerations I need to be aware of.

I will be covering this in a future post.  Meanwhile appreciate some feedback from the readers.

Tuesday, June 06, 2017

Sending Automatic Emails from SQL server

I am excited to reactivate my blog after 2.5 years.

I have written a stored procedure last week to send automated emails to customers based on certain criteria.

To identify this there is a stored procedure that requires some parameters.

The steps followed for creating the stored procedure are as follows:


  • There is already an existing stored procedure that creates a temp table and inserts data into that temp table.
  • In the new stored procedure define a new temp table.
  • Insert data into this temp table by executing the existing stored procedure
  • Declare new variables to hold the needed for the email.
  • In a while loop assign the data to the above variables for each record and send the email one by one using sp_send_dbmail built in stored procedure.
Here is the skeleton code I came up with for the procedure.  I have configured a HTML email

[code]


Declare @temp_table table
(
ID INT IDENTITY(1, 1) primary key ,
  field1 varchar(60) null,
AccountID VARCHAR(25) null,
AccountName varchar(200) null,
AccountEMail varchar(128) null
       )

--
-- Insert into the temp table variable -- the list to be emailed by running the stored procedure Proc1
--

Insert into @temp_table
(

  field1,
AccountID,
AccountName,
AccountEMail

)
Exec [Proc1]
@Parameter1 = 'NZIO',
@Parameter2 = 1,
@Parameter3=0


--
-- Declare new variables
--

DECLARE @count INT
DECLARE @accountemail varchar(60)
DECLARE @accountname varchar(60)
DECLARE @rowcount INT
DECLARE @href1 varchar(256)

--setting count to start from first row
SET @count = 1
SET @rowcount = (SELECT count(*) FROM @temp_table)
--Print @rowcount


--
--loop to send email from temp table
        --

WHILE(@count < @rowcount)
BEGIN
SET @accountemail = (SELECT AccountEMail FROM @temp_table where Id = @count and AccountEMail LIKE '%_@__%.__%')
SET @accountname = (SELECT AccountName FROM @temp_table where Id = @count and AccountEMail LIKE '%_@__%.__%')
SET @href1 = (SELECT CASE When ClientMode = 'UNATTENDED (HANDS-FREE)' then 'http://link1.pdf' else 'http://link.pdf' END FROM @temp_table where Id = @count and AccountEMail LIKE '%_@__%.__%')


--
--Configure Email body
--

DECLARE @tableHTML  NVARCHAR(MAX) ;

SET @tableHTML =
N'

Automatic Notification -- Please do not reply

' +
N'Good Morning  ' +
cast(@accountname as nvarchar(max)) +
N' We are contacting you to let you know that blah blah (EDI: ' +
cast(@field1 as nvarchar(max)) +
N')
is not working.  Please have a look at your account+ cast(@accountname as nvarchar(max)) +
N' Please click on the below link to view user guide on starting
' + N' Userguide for Windows ' +
N' Regards BI Support '

;

--
-- Send email using Database Mail
--

--USE msdb
--GO
EXEC MSDB.dbo.sp_send_dbmail @profile_name='Testreport',
@copy_recipients = @accountemail,
@recipients = 'iemail@emailadd.com',
@subject='Test message',
@body= @tableHTML,
@body_format = 'HTML' ;



SET @count= @count +1

END


[/code]





Wednesday, February 26, 2014

Getting the first date of the month in SQL without any functions

One of the date columns in my database is an integer as it is a dimension key
I was trying to get some results grouped for the whole month by this date integer column.

This is how I went about getting it in an easier manner without using any DATEADD and DATDIFF functions

Let us say that the date column name is dim_date_key which is an integer data type

So I used the following SQL code to get the sum of the amount for the month

select sum(amount), dim_date_key/100*100 + 1 month_start_Date from table_name
where dim_date_key/100*100 + 1 >= 20130401
group by dim_date_key/100*100 + 1

Here if we just look at the expression dim_process_date_key/100*100 +1 in mathematical terms it is confusing as to how this can get the start of the month.

But the key here is the integer data type of the date column.


  • When the expression is evaluated, the expression dim_process_date_key/100 gets evaluated first.  This gives the answer as 201304 since the data type is an integer.
  • Then the expression 201304 * 100 is evaluated which yeilds the result as 20130400 which is an integer.  
  • Then the expression 20130400 + 1 is evaluated which yeilds the start date of the month which is 20130401


Tuesday, December 13, 2011

Have you heard of space function?

Today I had a unique scenario where I had to introduce 2 spaces in between two fields.

I came across the space function which I used in my scenario.

The syntax is space(integer_expression)

The integer expression is an integer. IF a negative value is supplied a null is returned.

So for example look at the following syntax:

select First_name, + space(4) + Last_Name from test_table

The above select statement will generate 4 spaces in between the first name and last name

The space function will generate a miximum of 8000 spaces.
For more information click here

Wednesday, September 14, 2011

Save SQL Query results into another SQL database

Today I had a requirement to save the results of an SQL query into a sql table. Usually it is easy to export to excel by using the option of copying the results and pasting them to an excel file.

But this time I had over a million rows and I didnot want to use excel to store that huge amount of data. So I followed the following 2 simple steps.

1. Create a new table in a new database:

Use the SSMS to create the database and use the create table query to create the new table as follows:

create table databasename.dbo.tablename

([col1] [varchar(20)], [col2] [int], [col3] [datetime])

2. Create a SQL query using the Insert into command as follows:

Insert into databasename.dbo.tablename

(col1, col2, col3)

select a.col1, b.col2, c.col3 from tab1 a, tab2 b, tab3 c

where a.col1=b.col1 and b.col2=c.col3 and col1='zzz'

This query has inserted data into the new table directly.

Tuesday, August 30, 2011

Using the script task in Management Studio

Today I was taking a back of a database and for the past two days this has become my regular activity. So I thought there should be some kind of recording option (like recording a macro in excel) so that I can just use the recorded action whenever I need to do the same task again and again.

So I tried to investigate and found this script button. So I thought I would investigate this. The following are the steps I followed to backup a database in the Management Studio.


  • Right click the database that needs to be backed up.

  • Click on Task -- Backup

  • Choose the Backup options like how you choose normally.

  • Before clicking Ok click on the Script option at the top and choose the option that you want from the 4 options available as shown below.





This has generated a nice script as shown below.

BACKUP
DATABASE [TEST] TO

DISK

= N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\TEST20110830.bak' WITH FORMAT, INIT, MEDIANAME = N'TEST', NAME = N'TEST-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO


This script can be used to do the same task again and again and also may be you can schedule this to be processed at a certain time every day.



Thursday, July 14, 2011

Free TSQL Webcasts Start Next Week



In SSWUG.ORG’s “Writing T-SQL Queries and Code” webcast series, you will be able to learn how to write aggregate and crosstab queries, as well as how to use common table expressions to write recursive queries.

In three, in-depth sessions, Kathi Kellenberger, SQL Server Technology Specialist for Microsoft and author of Beginning T-SQL 2008, will teach beginning and experienced T-SQL programmers about writing code to ensure their applications are highly performing.

By the end of the series, you will be more familiar with T-SQL queries and know how to simplify your work through new and advanced features.

Learn more about the virtual webcast content and register today.

Tuesday, January 25, 2011

SQL Bits Content

I came across this link on SQL Bits where there are about 164 videos on various aspects of SQL Server and sharepoint which I found useful. Altogether there are 215 articles.

Have a look at the compiled sessions and content page.

Wednesday, November 10, 2010

Grant and Revoke Privileges

Today I have accidentally given access to a user using the grant option by issuing the Grant sql command.

GRANT VIEW ANY DATABASE TO username;

GO

I have immediately realised that I didn't want to give access to that user and hence I had to revoke the permissions.

REVOKE VIEW ANY DATABASE From username;

Thought I would document this here so that any one doing the same would benefit from this.

Also there is a With Grant option that you can use while using Grant option.

The main difference between Grant and With Grant option is that --
If only GRANT is used, the user cannot grant the same permission to other users.

Friday, November 05, 2010

The hardly used stuff function

My share of todays learning at sql share is the unusual stuff function. I have not heard of this function before and here are my learnings from the video by Andy Warren.
  • Stuff function inserts a string into a string at a specified position. It feels a bit like REPLACE (and you can certainly use it that way), but it's really designed to do something different - push x characters into a string based on an index and length.
  • Andy was surprised to realize it was the only string function he had never used to solve a problem.
  • If you try to use the stuff function to insert a null at a certain position of the string to replace a few characters, it does not error but it just returns the remaining characters after removing the number of characters you have specified.
  • If you try to use the stuff function that has null in its string, no matter what you try to replace it with it returns null

To learn more watch the video by Andy Warren.

Power BI Kids competition 2026

 Celebrating the next generation of data rockstars! 🚀✨ I am incredibly proud to share that we have officially wrapped up our 8-week #PowerB...