TechBrothersIT is the blog spot and a video (Youtube) Channel to learn and share Information, scenarios, real time examples about SQL Server, Transact-SQL (TSQL), SQL Server Database Administration (SQL DBA), Business Intelligence (BI), SQL Server Integration Services (SSIS), SQL Server Reporting Services (SSRS), Data Warehouse (DWH) Concepts, Microsoft Dynamics AX, Microsoft Dynamics Lifecycle Services and all other different Microsoft Technologies.
In this video you will learn how to save query results in TEXT, Report or Excel format. It explains different options to save query results such as in Text file, in grid and in reporting (.rpt) format. It also shows how to save query results with header (column names) in SQL Server Management studio.
How to Save Query Results to Text or Excel File From SSMS
This video explain how to find out SQL Server Configuration Changes in last hour, how to find out who and what changed in SQL Server Configurations. It shows multiple ways of looking at the SQL Server configuration changes history, what is default trace in SQL Server, how to enable and disable default trace in SQL Server, best practices to define SQL Server Configuration changes history retention period, location of default trace in SQL Server, how to read default trace event selection using T-SQL Script, how to open default trace in SQL Server Profiler and resolution to the error " Failed to open the trace, Access denied"
Script for the video: How to Find out SQL Server Configuration Changes
SELECT *
FROM fn_trace_gettable
('C:\Program Files\Microsoft SQL Server\MSSQL12.SQLTEST\MSSQL\Log\log_56.trc', default);
GO
exec sp_executesql @stmt=N'begin try
declare @enable int;
select @enable = convert(int,value_in_use) from sys.configurations where name = ''default trace enabled''
if @enable = 1 --default trace is enabled
begin
declare @d1 datetime;
declare @diff int;
declare @curr_tracefilename varchar(500);
declare @base_tracefilename varchar(500);
declare @indx int ;
declare @temp_trace table (
textdata nvarchar(MAX) collate database_default
, login_name sysname collate database_default
, start_time datetime
, event_class int
);
select @curr_tracefilename = path from sys.traces where is_default = 1 ;
set @curr_tracefilename = reverse(@curr_tracefilename)
select @indx = PATINDEX(''%\%'', @curr_tracefilename)
set @curr_tracefilename = reverse(@curr_tracefilename)
set @base_tracefilename = LEFT( @curr_tracefilename,len(@curr_tracefilename) - @indx) + ''\log.trc'';
insert into @temp_trace
select TextData
, LoginName
, StartTime
, EventClass
from ::fn_trace_gettable( @base_tracefilename, default )
where ((EventClass = 22 and Error = 15457) or (EventClass = 116 and TextData like ''%TRACEO%(%''))
select @d1 = min(start_time) from @temp_trace
set @diff= datediff(hh,@d1,getdate())
set @diff=@diff/24;
select (row_number() over (order by start_time desc))%2 as l1
, @diff as difference
, @d1 as date
, case event_class
when 116 then ''Trace Flag '' + substring(textdata,patindex(''%(%'',textdata),len(textdata) - patindex(''%(%'',textdata) + 1)
when 22 then substring(textdata,58,patindex(''%changed from%'',textdata)-60)
end as config_option
, start_time
, login_name
, case event_class
when 116 then ''--''
when 22 then substring(substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))
,patindex(''%changed from%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata)))+13
,patindex(''%to%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))) - patindex(''%from%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))) - 6)
end as old_value
, case event_class
when 116 then substring(textdata,patindex(''%TRACE%'',textdata)+5,patindex(''%(%'',textdata) - patindex(''%TRACE%'',textdata)-5)
when 22 then substring(substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))
,patindex(''%to%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata)))+3
, patindex(''%. Run%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))) - patindex(''%to%'',substring(textdata,patindex(''%changed from%'',textdata),len(textdata) - patindex(''%changed from%'',textdata))) - 3)
end as new_value
from @temp_trace
order by start_time desc
end else
begin
select top 0 1 as l1, 1 as difference,1 as date , 1 as config_option,1 as start_time , 1 as login_name, 1 as old_value, 1 as new_value
end
end try
begin catch
select -100 as l1
, ERROR_NUMBER() as difference
, ERROR_SEVERITY() as date
, ERROR_STATE() as config_option
, 1 as start_time
, ERROR_MESSAGE() as login_name
, 1 as old_value, 1 as new_value
end catch',@params=N''
How to Find out SQL Server Configuration Changes in last Hour
In this video you will learn multiple ways of how to enable and disable SQL Server Agent Job, how to schedule jobs that would run in later hours using SQL Server Management Studio as well as T-SQL script. It also explains how to enable or disable Job Schedule as well as how to update SQL Server Agent Job Schedule.
Scripts to Enable or Disable SQL Server Agent Jobs or Schedule to Start Later on Schedule
In this video you will learn how to avoid using C drive as SQL Server Database data or/and log files. It also explains what are the drawbacks of using C:\ drive as SQL Server database data drive or log drive. You will learn how to look at SQL Server database settings and how to change default database data and log file location. Video explains step by step process of changing SQL Server Database settings along with pre-requisites of these changes to be in effect.
Script used in the video To avoid C drive for database create in SQL Server
USE [master]
GOEXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\Data'GOEXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'L:\Data'
GO
Avoid Using C drive for Database Create in SQL Server - DBA Tutorial
In this video you will learn multiple ways of how to disable maintenance plan temporarily using SQL Server Management studio. It also explains how to enable or disable tasks in the Maintenance plans.
How to Temporarily Disable Maintenance Plan in SQL Server
In this video you will learn step by step process of starting SQL Server Profiler automatically after SQL Server services restart. It shows how to create a sample trace using SQL Server Profiler (GUI), how to export Trace settings to a file, how to provide trace location, how to create store procedure from the trace definition, how to execute store procedure to verify if trace is running on the SQL Server, how to Mark Store procedure to run at start up in SQL Server, how to enable store procedure startup scan in SQL Server Configuration and finally how to check if the settings are working after SQL Server restarts.
Script used in the video To Automatically Restart SQL Profiler after SQL Server Service Restart
--see if trace is runningselect * from sys.traces
--Mark Trace Store Proc startup option TrueEXEC sp_procoption 'StoreProcName', 'startup', 'true';
--Verify start option value is 1USE MASTER
GOSELECTVALUE, VALUE_IN_USE, DESCRIPTION
FROM SYS.CONFIGURATIONS
WHERE NAME = 'scan for startup procs'GOCreateproc SPTroubelTrace
/****************************************************/
/* Created by: SQL Server 2014 Profiler */
/* Date: 03/28/2015 03:44:23 PM */
/****************************************************/
AS-- Create a Queuedeclare @rc intdeclare @TraceID intdeclare @maxfilesize bigint
set @maxfilesize = 5
-- Please replace the text InsertFileNameHere, with an appropriate-- filename prefixed by a path, e.g., c:\MyFolder\MyTrace. The .trc extension-- will be appended to the filename automatically. If you are writing from-- remote server to local drive, please use UNC path and make sure server has-- write access to your network sharedeclare @TrcFileName nvarchar(300)
set @TrcFileName = N'C:\STARTTrace'+CAST(DATEPART(d,GETDATE()) ASvarchar(2))+CAST(DATEPART(M,GETDATE()) ASvarchar(2))+CAST(DATEPART(YYYY,GETDATE()) ASvarchar(4))+CAST(DATEPART(HH,GETDATE()) ASvarchar(2))+CAST(DATEPART(MI,GETDATE()) ASvarchar(2))
exec @rc = sp_trace_create @TraceID output, 0, @TrcFileName, @maxfilesize, NULLif (@rc != 0) goto error
-- Client side File and Table cannot be scripted-- Set the eventsdeclare @onbitset @on = 1
exec sp_trace_setevent @TraceID, 14, 1, @onexec sp_trace_setevent @TraceID, 14, 2, @onexec sp_trace_setevent @TraceID, 14, 3, @onexec sp_trace_setevent @TraceID, 14, 12, @onexec sp_trace_setevent @TraceID, 14, 14, @onexec sp_trace_setevent @TraceID, 14, 26, @onexec sp_trace_setevent @TraceID, 14, 35, @onexec sp_trace_setevent @TraceID, 15, 3, @onexec sp_trace_setevent @TraceID, 15, 12, @onexec sp_trace_setevent @TraceID, 15, 14, @onexec sp_trace_setevent @TraceID, 15, 26, @onexec sp_trace_setevent @TraceID, 15, 35, @onexec sp_trace_setevent @TraceID, 17, 1, @onexec sp_trace_setevent @TraceID, 17, 2, @onexec sp_trace_setevent @TraceID, 17, 3, @onexec sp_trace_setevent @TraceID, 17, 12, @onexec sp_trace_setevent @TraceID, 17, 14, @onexec sp_trace_setevent @TraceID, 17, 26, @onexec sp_trace_setevent @TraceID, 17, 35, @onexec sp_trace_setevent @TraceID, 11, 2, @onexec sp_trace_setevent @TraceID, 11, 3, @onexec sp_trace_setevent @TraceID, 11, 12, @onexec sp_trace_setevent @TraceID, 11, 14, @onexec sp_trace_setevent @TraceID, 11, 26, @onexec sp_trace_setevent @TraceID, 11, 34, @onexec sp_trace_setevent @TraceID, 11, 35, @onexec sp_trace_setevent @TraceID, 43, 1, @onexec sp_trace_setevent @TraceID, 43, 3, @onexec sp_trace_setevent @TraceID, 43, 12, @onexec sp_trace_setevent @TraceID, 43, 14, @onexec sp_trace_setevent @TraceID, 43, 22, @onexec sp_trace_setevent @TraceID, 43, 26, @onexec sp_trace_setevent @TraceID, 43, 34, @onexec sp_trace_setevent @TraceID, 43, 35, @onexec sp_trace_setevent @TraceID, 42, 1, @onexec sp_trace_setevent @TraceID, 42, 3, @onexec sp_trace_setevent @TraceID, 42, 12, @onexec sp_trace_setevent @TraceID, 42, 14, @onexec sp_trace_setevent @TraceID, 42, 22, @onexec sp_trace_setevent @TraceID, 42, 26, @onexec sp_trace_setevent @TraceID, 42, 34, @onexec sp_trace_setevent @TraceID, 42, 35, @onexec sp_trace_setevent @TraceID, 44, 1, @onexec sp_trace_setevent @TraceID, 44, 3, @onexec sp_trace_setevent @TraceID, 44, 12, @onexec sp_trace_setevent @TraceID, 44, 14, @onexec sp_trace_setevent @TraceID, 44, 22, @onexec sp_trace_setevent @TraceID, 44, 26, @onexec sp_trace_setevent @TraceID, 44, 34, @onexec sp_trace_setevent @TraceID, 44, 35, @onexec sp_trace_setevent @TraceID, 13, 1, @onexec sp_trace_setevent @TraceID, 13, 3, @onexec sp_trace_setevent @TraceID, 13, 12, @onexec sp_trace_setevent @TraceID, 13, 14, @onexec sp_trace_setevent @TraceID, 13, 26, @onexec sp_trace_setevent @TraceID, 13, 35, @on-- Set the Filtersdeclare @intfilter intdeclare @bigintfilter bigint
-- Set the trace status to startexec sp_trace_setstatus @TraceID, 1
-- display trace id for future referencesselect TraceID=@TraceID
goto finish
error:
select ErrorCode=@rc
finish:
go
In this video you will learn how to run SQL Server Agent Job in a Batch file, it explains step by step process of creating a batch file using SQLCMD, connecting with target SQL Server, database and running SQL Server Store procedure from a batch file. It also shows step by step process of creating and scheduling batch job in windows scheduler instead of using SQL Server Agent Scheduler.
Script used in video to Run SQL Server Agent Job from Batch File
In this video you will learn step by step process of creating SQL Server agent job that calls another job on same SQL Server instance or remote SQL Server using T-SQL Script. It also explains what is required to connect to remote SQL Server in this scenario (Creating Linked Server) or using power-shell script to connect to remote SQL Server. It also provides a resolution to an error " The server doesn't allow RPC connection or RPC is disabled on the server"
Script to call SQL Server Agent Job inside another SQL Server Agent Job from Same Server or other instance.
--Call another job on same SQL ServerUSE msdb
GOEXEC dbo.sp_start_job N'BackupAlldb'GO--Call another job on different SQL Server -- Requires Linked server EXEC [TBSSQL\SQLPROD].[msdb].dbo.sp_start_job N'BackupAlldb'
How to Call SQL Server Agent Job/s from Another SQL Server Agent Job
In this video you will learn how to configure Maximum number of concurrent connections in SQL Server using SQL Server Management studio as well as using T-SQL Script. Video also explains step by step process of going through advance options of SQL Server, what is default number of concurrent connection SQL Server allows and pre-requisites of concurrent connection settings to take effect in SQL Server.
Scripts used in the video to Configure Maximum Number of Concurrent Connections in SQL Server
On daily basis we come across different questions and scenarios as Database developers and DBAs. Sometime users just stop by and they ask us questions and tell us that they have a table in one of the database and if we can take a look for them. When we try to find out the table, we don't see the table.The table might be in different Database and user is not providing correct information.
The below script can be used to find out any object on Entire SQL Server Instance. you can use this script
To find a Table in all the Databases on SQL Server Instance
To find a Stored Procedure in All the Databases on SQL Server Instance
To find a view on entire SQL Server Instance
To find a function in any database on SQL Server Instance.
In short any object can be found by using below script. You only have to provide the name of object and it will return you information with Database Name, Schema Name, Object Name, Type and Type Description. The below code is also one of the example where we need to change the database name in our query and we can use Dynamic SQL to perform that.
--Provide The Object Name such as TableName,Stored Procedure, View,--Function etc that you find on Entire SQL SERVER INSTANCEDECLARE @ObjectName VARCHAR(100)
SET @ObjectName='Customer'-- Change the Customer to your ObjectName------------------------------------------------------------------------------------IF OBJECT_ID('tempdb..##Object') ISNOTNULLDROPTABLE ##ObjectCREATETABLE ##Object (
DatabaseName VARCHAR(500)
,ObjectName VARCHAR(500)
,SchemaName VARCHAR(100),
ObjectType VARCHAR(10),
ObjectDesc VARCHAR(100)
)
--Use Cursor to Loop through Databases to Find Object in SQL Server Instance DatabasesDECLARE @DatabaseName ASVARCHAR(500)
DECLARE DBCursor CURSORFORSELECT NAME
FROM sys.databases
OPEN DBCursor
FETCHNEXTFROM DBCursor
INTO @DatabaseName
WHILE@@FETCH_STATUS = 0
BEGINDECLARE @DBName AS NVARCHAR(500);
SET @DBName = QUOTENAME(N'' + @DatabaseName + '');
EXEC (
N'USE ' + @DBName + N'; EXEC(''
Insert into ##Object
Select DB_Name() AS DatabaseName,
name as ObjectName,
schema_name(schema_id) AS SchemaName,
Type,
type_desc From sys.objects
where is_ms_shipped=0
'');'
);
FETCHNEXTFROM DBCursor
INTO @DatabaseName
ENDCLOSE DBCursor
DEALLOCATE DBCursor
--Return the Object Name with DatabaseName,SchemaName,Type and Type Descripton. SELECT *
FROM ##Objectwhere ObjectName=@ObjectName
Find object ( Table,Stored Procedure, Function,View etc. in SQL Server)
Video Tutorial : How to Search Object Name on SQL Server Instance
We often have to add a new column to existing Table/s. Let's consider we have dbo.Customer table and we are US based company and we never did business outside USA. so we never need Country Column to our existing Table for Address as we only operator in USA. Now company has decided to expand the business and might have the customers from other countries. What we want to do , we want to add column to existing table with default value. All the existing values should be also updated to default value when we add this new column. Moving forward if no Country Name provided, It should take USA otherwise value provided.
--Create Sample Table without CountryName ColumnCreatetable dbo.Customer (
CustomerId IntIdentity(1,1),
CustomerName VARCHAR(100),
StreetAddress VARCHAR(100),
City VARCHAR(100),
StateCHAR(2))
--Insert couple of Records in Sample TableInsertinto dbo.Customer
Select'Aamir Shahzad','Test Street Address','Charlotte','NC'UnionSelect'M Raza','Test Street Address','Charlotte','NC'
Add the new column Without Providing NOT NULL Constraint
AlterTable dbo.Customer
ADD CountryName VARCHAR(50)
Default'USA'Select * From dbo.Customer
Fig 1: Add New Column to Existing SQL Server Table without Providing Not Null Constraint
In above query we did not mention the Not Null constraint for our CountryName column. SQL Server took that by default as Null. Also it did not update the newly added column with default values.
Add New Column With NOT NULL AND Default Constraint
If we will provide Not Null constraint for the CountryColumn and also default value. The newly added column will be populated with default values as shown below.
AlterTable dbo.Customer
ADD CountryName VARCHAR(50) NOTNULLDefault'USA'Select * from dbo.Customer
Fig 2: Add Not Null Constraint with Default Value To populate existing Column in Table
Now consider the last scenario, In which we want to keep our Column to accept Null values but populate existing records with default and add default constraint.
Add Column To Existing Table With Default Values and Column should accept Null as well. Also populate the Newly Added Column with Default Values at time of Adding Column
AlterTable dbo.Customer
ADD CountryName VARCHAR(50)
Default'USA'WITHValuesSelect * from dbo.Customer
Fig 3: Add New column with Null constraint and default value and populate with Default values
As you can see in last sql script we used "With values" clause. If you use that, the existing records will be populated with default values. Also as we did not provide NOT Null Constraint, our table will accept Null values in case we want to save Null value in column. If no value will be provided, default value will be inserted to the table.
--Check if Default is working fineInsertinto dbo.Customer(CustomerName,StreetAddress,City,State)
Select'John Smith','Test Street Address','Charlotte','NC'--Insert Null CountryNameInsertinto dbo.Customer(CustomerName,StreetAddress,City,State,CountryName)
Select'July River','Test Street Address','Jersey City','NJ',Null
Fig 4: Insert Records SQL Server Table after Adding New Column
SQL Server Video Tutorial: Watch the Video for Above Scenarios How to Add Column To SQL Table and populate already existing rows with default value.
By default isolation level of SQL Server Database Engine is READ COMMITTED. That mean if we try to select the rows, it will only return us only committed rows.
To Check the Default Isolation level of SQL Sever we can use
DBCC useroptions
Fig 1: DBCC useroptions output to check Isolation level of SQL Server
Let's consider couple of scenarios where we want to read uncommited data
We are deleting alot of records from Table and want to take a look on progress
We are inserting a lot of records by using SSIS Package, even the records are not committed, we want to see the progress of load.
OR
Sometime we are preparing our Scripts for deployments and we run the statement and then want to see if script worked as expected before committing the transaction.
WITH (NOLOCK) is hint that we can use to read dirty or uncommitted records.
Let's create a table in one of our Database by using below DDL Script and Insert couple of Records
USE TestDB
goCreateTable dbo.TblCustomer(
Id int,
NAME VARCHAR(100),
Region VARCHAR(100)
)
goinsertinto dbo.TblCustomer values (1,'Aamir',NULL)
goInsertinto dbo.TblCustomer values (2,'Raza',Null)
Now let's Begin our Transaction in a connection and update the Region Column with value='NA' as shown below.
BEGINTRANUpdate dbo.TblCustomer
set Region='NA'
Fig 2: Update the Records by using Begin Transaction in SQL Server
As we can see in Fig 2. Two rows are effected. As we did not Commit the Transaction. The records are still not committed to the table. Let's open a new query windows (Connection/Session) and try to Select the Rows from dbo.tblCustomer table.
Fig 3: Trying to read data from Table on which we have uncommitted transaction
As we can see that in Fig 3, It is trying to read the database but not returning anything. The reason it is not returning any results because we have Read Commit Isolation level on SQL Server Database Engine and records are not committed those we start updating in Fig 2. The query can only return committed records.
To read the uncommitted records we can use WITH (NOLOCK) hint and see the dirty or uncommitted rows.
Fig 4: Read uncommitted records by using WITH (NOLOCK) Hint in SQL Server
As we can see that we even did not commit the Transaction that we opened in Fig 2 but by using WITH ( NOLOCK) Hint on Table, we are table to read the dirty or uncommitted records. Now at this point if we feel that our script worked as expected, we can go ahead and commit Transaction by using COMMIT TRAN or we can rollback by using ROLLBACK TRAN.
SQL Server Video Tutorial: How to Read uncommitted Rows/ Dirty Records
To save Image file in a SQL Server Table first of all we need to have a column that can handle Image files. VARBINARY is data type that we can use to store Images or any other type of files. Let's create the Table with Varbinary Datatype and then import the image by using below script.
CREATETABLE dbo.TblPicture_Src (
ID INTIdentity(1, 1),NAMEVARCHAR(100),Picture VARBINARY(MAX))GO--Import Image/File from File System To SQL Server TableINSERT INTO dbo.TblPicture_Src (NAME,Picture
)SELECT'Capture1.PNG',BulkColumn
FROMOpenrowset(BULK'C:\4_Mypicture.PNG', Single_Blob)AS Picture
SELECT*FROM dbo.TblPicture_Src
Fig 1: How to Import Files to SQL Server Table by using TSQL in SQL Server
As you can see that we used OpenRowset to import the file to SQL Server table. To make this script work, Change the file path according to your input file.
We can also use SQL Server Integration Services (SSIS) Package to load the image or any other files from file system to SQL Server Table by using Import Column Transformation.
How to Import Files to SQL Server Table by SSIS Package
Working with Databases is fun. On daily basis we save data into tables in different columns and often we need to write queries which involve concatenation of multiple columns of different datatypes to produce our final output. In below example we have saved some data into #Customer Table which has Street Address column as string and zip as INT. we want to produce Full Address by concatenating these columns. To concatenate we can use + sign but this works only with String values. So if we have any Integer value/s we have to convert them to String first. We can use Cast or Convert function to convert Integer value to string. Also if there is any Null value among which values we are concatenating , our output will be Null by using + sign. To take care of that part we can use either ISNULL() or Coalesce Function to replace NULL with blank value in SQL Server.
In SQL Server 2012 and Later versions, CONCAT function was introduced. You can concatenate multiple values by using this function. Fun part of this function is you don't have to worry about Null outcome as it will Ignore Null values and also you don't have to worry about converting INT into strings, It will take care of that automatically. So if you are using new versions such as 2012 or later, start taking advantage of this function.
Createtable #TempCustomer (
Id int, Name VARCHAR(100),
StreetAddress VARCHAR(100),
Zip Int,
City VARCHAR(100))
goInsertinto #TempCustomer
Select 1,'Aamir','House# 000 Street ABC',28000,'Charlotte'UnionSelect 2,'Raza','House# 001 Street PJK',45000,'New York'UnionSelect 2,'Raza','House# 011 Street ATC',7500,'Harisburg'UnionSelect 2,'Raza','House# 222 Street ZZZ',2500,NULLUnionSelect 2,'Raza','House# 222 Street ZZZ',Null,'High Points'--By using Plus ( Sign)Select StreetAddress+' '+Cast(Zip ASVARCHAR(10))+' '+ City
AS FullAddress from #TempCustomer
--Have to Take care of Null Values by ourselves by using ISNULL Select ISNULL(StreetAddress,'')+' '+ ISNULL(Cast(Zip ASVARCHAR(10)),'')+' '+
ISNULL(City,'')
AS FullAddress from #TempCustomer
--Have to Take care of Null Values by ourselves by using Coalesce SelectCoalesce(StreetAddress,'')+' '+ Coalesce(Cast(Zip ASVARCHAR(10)),'')+' '+
Coalesce(City,'')
AS FullAddress from #TempCustomer
--USE CONCAT Function in SQL 2012 and Later Version, NULL values will be --ignored and we don't have to convert Zip( INT To VARCHAR), It will take care of conversionSelect Concat(StreetAddress,' ',Zip,' ',City) AS FullAddress from #TempCustomer
droptable #TempCustomer
Output from above Queries for String and Integer concatenation in SQL Server
TSQL Video Tutorial : How to use + Sign or CONCAT Function in SQL Server for Concatenation
ISNUMERIC( ) function is provided to us in SQL Server to check if the expression is valid numeric type or not. As per Microsoft it should work with Integers and Decimal data types and if data is valid integer or decimal, ISNumeric() should return us 1 else 0. But ISNUMERIC() does not work as expected with some of values specially when we have "-" or "d" in value and have two numbers after "d" such as 123d22, it still return us 1. Also if we have data in money format $XXXXX e.g $2000, It returns us 1.
In SQL Server 2012. Microsoft introduced new function call Try_Convert( ). You can use try_convert function to convert to required data type and if it is not able to convert then it will return Null as output. As you will see below, I did some experiment and found out that Try_Convert will produce 0 for "-" when we try to convert to Int, That should not be happening as "-" is symbol not Integer. But when I try to convert "-" to decimal, Try_Convert produced Null output.
Take a look in below results and keep in mind the outputs when you have to evaluate expression to Numeric or find out if expression is Numeric or Not.
USE TestDB
GOCREATETABLE #Customer (ColName VARCHAR(100))
GO--Insert some Sample DataINSERTINTO #Customer
Select'1-2'UnionSelect'54f54'UnionSelect'123'UnionSelect'123.09'UnionSelect'-'UnionSelect'24d09'UnionSelect'$200'UnionSelect'TestData'UnionSelect'Street 123'UnionSelect'123$'UnionSelect'$234$'UnionSelect'1.2'UnionSelect'1'UnionSelect'234-4'UnionSelect'_'--Use ISNUMERIC AND TRY_Convert Functions to Check if Given Records Are Numeric OR NOTSELECT ColName
,ISNUMERIC(ColName) AS ISNUMERIC_Function_Output
,try_convert(DECIMAL(18, 3), ColName) AS DecimalConversion
,TRY_CONVERT(INT, ColName) AS INTConversion
,CASEWHEN ColName='-'THEN'Not Numeric'WHEN try_convert(DECIMAL(18, 3), ColName) ISNOTNULLTHEN'NUMERIC'WHEN try_convert(INT, ColName) ISNOTNULLTHEN'NUMERIC'ELSE'Not Numeric'ENDAS IsNumericOrNot
FROM #Customer
GODroptable #customer
Fig 1: Using ISNUMERIC() or Try_Convert Function to evaluate if Expression is Numeric
SQL Server Video Tutorial: Learn Details of ISNUMERIC AND Try_Convert Function
We often come across different scenarios where we need to switch the database name inside stored procedure. Let's take a look for few of scenarios below
We have never introduced Audit Columns to our tables on SQL Server Instance such as ModifiedBy, ModifiedOn. Now we want to add these two columns to all the tables on SQL Server Instance.
We want to get the record count for all the tables in SQL Server Instance. That includes any Database on our Current SQL Server Instance.
We have enabled CDC on multiple Databases on our SQL Server Instance, we want to get the list of tables from multiple Databases on which CDC is enabled.
In all above scenarios we have to switch Database to get the required results. In our below example we are creating a stored procedure that should return us all the user tables on SQL Server Instance from User databases with record count. To get the record count we have to run our query on each Database. We will be using Dynamic SQL to change the database scope for our query so we can get results from that Database.
You can use Dynamic SQL to change the Database Name and run query against that database as shown in below example.
USE Test
GOCREATEPROCEDURE dbo.GetTableRecordCountForSQLInstance
ASBEGIN--Drop Temp table if exists to save record count for all the tables on SQL Server InstanceIF OBJECT_ID('tempdb..##RecordCount') ISNOTNULLDROPTABLE ##RecordCount
CREATETABLE ##RecordCount (
DatabaseName VARCHAR(500)
,TableName VARCHAR(500)
,RecordCount INT
)
--Use Cursor to Loop through DatabasesDECLARE @DatabaseName ASVARCHAR(500)
DECLARE CDCCursor CURSORFORSELECT NAME
FROM sys.databases
WHERE database_id > 4
OPEN CDCCursor
FETCHNEXTFROM CDCCursor
INTO @DatabaseName
WHILE@@FETCH_STATUS = 0
BEGINDECLARE @DBName AS NVARCHAR(500);
SET @DBName = QUOTENAME(N'' + @DatabaseName + '');
--USE Dynamic SQL To change the Database Name EXEC (
N'USE ' + @DBName + N'; EXEC(''
Insert into ##RecordCount
Select DB_Name() AS DatabaseName,t.name,s.rows from sysindexes s
inner join sys.tables t
on s.id=t.object_id
and t.is_ms_shipped=0
'');'
);
FETCHNEXTFROM CDCCursor
INTO @DatabaseName
ENDCLOSE CDCCursor
DEALLOCATE CDCCursor
--Return DatabaseName,TableName and Record Count from Temp TableSELECT *
FROM ##RecordCount
END
You can create this stored procedure in any of the Database you want. Once you run the Stored Procedure, It is going to get the user databases list and then use Cursor to loop through. Inside the Cursor we are using Dynamic SQL to change the scope of Query to Database by using USE statement.
SQL Server Video Tutorial: Detailed Video how to Change DB Name inside Stored Procedure
In this video you will learn about Model DataBase. Model Database is system Database in SQL Server that is used as template when we create New Database in SQL Server.
In this video you will learn following Items
How to Create Objects such as Tables, Views, Functions those we want to Create By default in any newly Create Database by using Model Database
What are the restrictions on Model Database
What Settings/Configurations are used in TempDB from Model Database
Does Create Database Statement take all the settings/Configurations of Model Database
Does GUI ( Graphical User Interface) copy the setting from Model for New Database Create Process
What is Model Database in SQL Server - SQL Server Tutorial