<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>&#60;jco-blog&#047;&#62; &#187; SQL Server</title>
	<atom:link href="http://www.elementalp.com/blog/index.php/tag/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.elementalp.com/blog</link>
	<description>Software Development Project Notes</description>
	<lastBuildDate>Tue, 05 Jan 2016 18:59:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>Close All Connections and Drop Database</title>
		<link>http://www.elementalp.com/blog/index.php/2015/05/26/close-all-connections-and-drop-database/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/05/26/close-all-connections-and-drop-database/#comments</comments>
		<pubDate>Tue, 26 May 2015 21:23:03 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=131</guid>
		<description><![CDATA[[crayon-6a2fcd36a77dc707014357/] Using setvar in T-SQL [crayon-6a2fcd36a7818826872585/]]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">originally posted 2013-9-11</pre><p><a href="http://www.elementalp.com/blog/index.php/2015/06/24/sql-cmd/">Using setvar in T-SQL </a></p>
</pre>
<p></p><pre class="crayon-plain-tag">:setvar db &quot;mydb&quot;
alter database $(db)
set restricted_user with rollback after 60 seconds
alter database $(db)
set single_user with rollback immediate
alter database $(db) set multi_user
drop database $(db)</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/05/26/close-all-connections-and-drop-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Application-Level Locking and Progress Reporting for Long Running Queries</title>
		<link>http://www.elementalp.com/blog/index.php/2015/05/26/simple-application-level-locking-and-progress-reporting-for-long-running-queries/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/05/26/simple-application-level-locking-and-progress-reporting-for-long-running-queries/#comments</comments>
		<pubDate>Tue, 26 May 2015 20:45:05 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=123</guid>
		<description><![CDATA[[crayon-6a2fcd36afa77485227658/] [crayon-6a2fcd36afab5835561200/]]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">originally posted 2014-03-24</pre><p></p><pre class="crayon-plain-tag">IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[System]') AND type in (N'U'))
DROP TABLE [dbo].[System]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fIsLocked]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fIsLocked]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fGetLockProgress]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fGetLockProgress]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fGenerateLockName]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fGenerateLockName]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTest]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetProgress]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetProgress]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetLock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetLock]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLongRunningQuery]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLongRunningQuery]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spIsLockedWait]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spIsLockedWait]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spClearLock2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spClearLock2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spClearLock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spClearLock]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCancel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCancel]
GO

CREATE TABLE [dbo].[System](
  [Id] [uniqueidentifier] NOT NULL default newsequentialid(),
  [Lock] [nvarchar](100) NULL,
  [LockDateTime] [datetime] NULL,
  [Progress] [int] NULL,
  [Cancel] [bit] NOT NULL default 0,
  [LockWaitTimeoutSeconds] [int] NOT NULL default 10,
  [LockExpireMinutes] [int] NOT NULL default 5,
 CONSTRAINT [PK_System] PRIMARY KEY CLUSTERED 
(
  [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

TRUNCATE TABLE [dbo].[System]
GO

INSERT [dbo].[System] ([Progress]) values (null)
GO

create procedure [dbo].[spCancel]
as
begin
  if([dbo].[fIsLocked]() = 1) update [dbo].[System] set [Cancel] = 1
end
GO

create procedure [dbo].[spClearLock](@lockname nvarchar(100) = null) as
begin
  update [dbo].[System] 
  set [Lock] = null
  where [Lock] like @lockname
end
GO

create procedure [dbo].[spClearLock2] as
begin
  update [dbo].[System] set [Lock] = null
end
GO

create procedure [dbo].[spIsLockedWait] (@waitForSeconds int)
as
begin
  --if @waitForSeconds &amp;amp;gt; 0 then wait for @waitForSeconds for the lock to clear
  --if @waitForSeconds = 0 then don't wait for the lock to clear
  --if @waitForSeconds is null then use system setting
  --if @waitForSeconds &amp;amp;lt; 0 then wait until the is cleared.
  --returns 1 if locked, else 0
  if (@waitForSeconds is null) select top 1 @waitForSeconds = [LockWaitTimeoutSeconds] from [dbo].[System] with (nolock)
  
  declare @dt datetime = getdate()
  declare @timedout bit = 0

  while([dbo].[fIsLocked]()=1)
  begin
    if(@waitForSeconds=0 or (@waitForSeconds &amp;amp;gt; 0 and datediff(s,@dt,getdate())&amp;amp;gt;@waitForSeconds))
    begin
      set @timedout = 1
      break;
    end
    waitfor delay '0:00:01';
  end

  if(@timedout=1) return [dbo].[fIsLocked]();
  return 0;
end
GO

create procedure [dbo].[spSetLock](@lockname nvarchar(100), @waitSeconds int) as
begin
  --if @waitForSeconds &amp;amp;gt; 0 then wait for @waitForSeconds for the lock to clear
  --if @waitForSeconds = 0 or null then don't wait for the lock to clear
  --if @waitForSeconds is null then use System.[LockTimeoutMinutes] value
  --if @waitForSeconds &amp;amp;lt; 0 then wait until the is cleared.
  
  if ([dbo].[fIsLocked]()=0)
  begin
    --set lock
    update [dbo].[System] set [Lock] = @lockname, [LockDateTime] = getdate();
    return 0;
  end
  else
  begin
    --lock already set
    declare @lockExpireMinutes int
    declare @LockDateTime datetime

    select top 1 
    @lockExpireMinutes = [LockExpireMinutes] 
    ,@LockDateTime = [LockDateTime]
    from [dbo].[System] with (nolock)

    if((select datediff(n, @LockDateTime, getdate())) &amp;amp;lt; @lockExpireMinutes)
    begin
      --not within the automatic clear time of @lockExpireMinutes

      --wait for lock for @waitSeconds
      declare @islocked bit = null;
      exec @islocked = [dbo].[spIsLockedWait] @waitSeconds
      if(@islocked = 0)
      begin
        --the existing lock cleared in time, set a new lock
        update [dbo].[System] set [Lock] = @lockname, [LockDateTime] = getdate();
      end
      else
      begin
        declare @msg nvarchar(max) = 'The system is currently running a locking process ''' + (select top 1 [Lock] from [dbo].[System]) + ''' that has locked the requested resources. You may try again once the running process completes.'
        raiserror(@msg,11,100);
        return -1;
      end
    end
    else
    begin
      --automatically clear the existing lock after @lockTimeoutMinutes and set a new lock
      update [dbo].[System] set [Lock] = @lockname, [LockDateTime] = getdate();
      return 0;
    end
  end
end
GO

create procedure [dbo].[spSetProgress](@percent int) as
begin
  declare @isLocked bit = [dbo].[fIsLocked]();
  if(@percent &amp;amp;lt;= 0) set @percent = 1;
  if(@percent is null or @percent &amp;amp;gt; 100 or @isLocked = 0) set @percent = 100;

  update [dbo].[System] set [Progress] = @percent

  if(@isLocked = 1) 
  begin
    declare @cancel bit = 0
    select top 1 @cancel = [Cancel] from [dbo].[System] with (nolock)
    if(@cancel = 1) 
    begin
      update [dbo].[System] set [Cancel] = 0 --clear cancel flag 
      raiserror(' cancel requested.',11,100);
      return -1;
    end
  end
end
GO

create function  [dbo].[fGenerateLockName](@seedname nvarchar(50) = null)
returns nvarchar(100)
as
begin
  declare @name nvarchar(100) = convert(nvarchar(25),datediff(s,'1970-1-1',sysutcdatetime()));
  if(@seedname is not null) set @name = @seedname + '_' + @name;
  return @name;
end
GO

create function [dbo].[fGetLockProgress]() returns nvarchar(100)
as
begin
  declare @progress int = 100;
  if([dbo].[fIsLocked]()=1)
  begin
    select @progress = [Progress]
    from [dbo].[System] with (nolock)
  end
  return @progress;
end
GO

create function [dbo].[fIsLocked]() returns bit 
as
begin
  if exists(select top 1 [Lock] 
  from [dbo].[System] with (nolock) 
  where [Lock] is not null and len(ltrim(rtrim([Lock])))&amp;amp;gt;0) return 1;
  return 0;
end
GO

create procedure [dbo].[spLongRunningQuery]
as
begin
  declare @errored bit = 0;
  declare @msg nvarchar(4000)
  declare @intrans bit = 0;
  declare @lock_result int = null;
  declare @lock nvarchar(100) = [dbo].[fGenerateLockName]('spLongRunningQuery');
  declare @count int = 0;

  begin try
    --acquire lock
    exec @lock_result = [dbo].[spSetLock] @lock, null

    exec [dbo].[spSetProgress] 10

    begin transaction
    set @intrans = 1

    while(@count&amp;amp;lt;100)
    begin
        exec [dbo].[spSetProgress] @count
      set @msg = convert(nvarchar(10),@count)
      raiserror (@msg, 0, 1) with nowait --print immediately
      waitfor delay '0:00:01'; --pause for a second
      set @count = @count + 10
    end

    commit transaction

  end try
  begin catch
    --handle error
    set @errored = 1;
    set @msg = 'Error : ' + isnull(error_message(),'');
    
    if (@intrans = 1) 
    begin
      rollback transaction
    end
  end catch

  --finalize
  if(@lock_result = 0) 
  begin
    --last progress update, ignore any error thrown
    begin try
      exec [dbo].[spSetProgress] 100
    end try
    begin catch
      dummy:
    end catch

    --release lock
    exec [dbo].[spClearLock] @lock
  end

  if(@errored=1) 
  begin
    raiserror(@msg,11,100);
    return -1
  end 
  return 0;
end
GO

create procedure [dbo].[spTest]
as
begin
  --TEST QUERY
  --STEP 1 : exec [spLongRunningQuery]
  --STEP 2 : Run this test query
  --NOTE: execute [spCancel] to cancel and rollback changes of [spLongRunningQuery]

  declare @msg nvarchar(300)
  declare @percent int = ''
  declare @lpercent int = ''

  while(1=1)
  begin
    if([dbo].[fIsLocked]()=1)
    begin
      set @percent = [dbo].[fGetLockProgress]() 
      set @msg = 'Progress : ' +  convert(nvarchar(100),@percent) + ' percent'
      if(@lpercent&amp;amp;lt;&amp;amp;gt;@percent) raiserror (@msg, 0, 1) with nowait --print immediately
      set @lpercent = @percent
    end
    else break;

    waitfor delay '0:00:00';
  end
  raiserror ('done.', 0, 1) with nowait --print immediately
end
GO</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/05/26/simple-application-level-locking-and-progress-reporting-for-long-running-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Change value of a given field for all records in all tables</title>
		<link>http://www.elementalp.com/blog/index.php/2015/05/26/change-value-of-a-given-field-for-all-records-in-all-tables/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/05/26/change-value-of-a-given-field-for-all-records-in-all-tables/#comments</comments>
		<pubDate>Tue, 26 May 2015 16:50:32 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=96</guid>
		<description><![CDATA[[crayon-6a2fcd36b05ea648491286/] Using setvar in T-SQL This example changes the value of the [Namespace] field for all records of all tables where the column is found. [crayon-6a2fcd36b0624171307552/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">originally posted 2014-12-22</pre><p></p>
<p><a href="http://www.elementalp.com/blog/index.php/2015/06/24/sql-cmd/">Using setvar in T-SQL</a></p>
<p>This example changes the value of the [Namespace] field for all records of all tables where the column is found.</p>
<p></p><pre class="crayon-plain-tag">:setvar DB &quot;foo&quot;
:setvar OLDNAMESPACE &quot;foo&quot;
:setvar NEWNAMESPACE &quot;bar&quot;

use $(DB)
GO
 
ALTER DATABASE $(DB) SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
select 'set database to single-user mode'
GO
 
exec sp_MSforeachtable '
    alter table ? disable trigger all;
    alter table ? nocheck constraint all;'
select 'disable triggers and constraints'
GO
 
begin try
    begin transaction
    print 'begin transaction'
 
    declare @sql nvarchar(max)
    select top 1000000
    @sql = substring(
    (
    select 
    --'select distinct [Table] = ''' + t.[Name] + ''',[Namespace] from [' + t.[Name] + '];'
    'update [' + t.[Name] + '] set [Namespace] = ''$(NEWNAMESPACE)'' where [Namespace] = ''$(OLDNAMESPACE)'';'
    from sys.tables t
    inner join sys.columns c  on c.object_id = t.object_id 
    where t.type = 'U'
    and c.[Name] = 'namespace'
    order by t.name
    for xml path('')
    )
    ,1,1000000)
 
    --select @sql
    exec(@sql);
     
    commit transaction
    select 'commit transaction'
end try
begin catch
    rollback transaction
    print 'rollback transaction'
    select 'error : ' + error_message()
end catch
 
--enable triggers and constraints for the db
exec sp_MSforeachtable '
    alter table ? enable trigger all;
    alter table ? check constraint all;'
GO
select 'enable triggers and constraints'
 
ALTER DATABASE $(DB) SET MULTI_USER;
select 'set to multi-user'
GO</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/05/26/change-value-of-a-given-field-for-all-records-in-all-tables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Problems with Floats as keys.</title>
		<link>http://www.elementalp.com/blog/index.php/2015/05/26/problems-with-floats-as-keys/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/05/26/problems-with-floats-as-keys/#comments</comments>
		<pubDate>Tue, 26 May 2015 16:34:34 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=86</guid>
		<description><![CDATA[[crayon-6a2fcd36b0dfb074621966/] Working with a product that uses floats as database keys :^o This has two solutions to generate float keys. [crayon-6a2fcd36b0e33845990433/]]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">originally posted 2015-01-20</pre><p>Working with a product that uses floats as database keys :^o<br />
This has two solutions to generate float keys.</p><pre class="crayon-plain-tag">--ONE WAY
SELECT [OneWay] = convert(float(53),getdate()) + ABS(CHECKSUM(NewId())) % 9999999 + ((ABS(CHECKSUM(NewId())) % 999999) * 0.10) + ((ABS(CHECKSUM(NewId())) % 999999) * 0.010)

declare @wholePart int
select @wholePart = case when [Seed] is not null then [Seed] else 1 end from (select [Seed] = convert(int,max([ctrAttachmentId])+1) from [tblAttachments]) as x
select [WholePart] = @wholePart

--ANOTHER WAY
create function GetId(@wholePart int, @seed uniqueidentifier)
returns float
as
begin
  return convert(float(52),convert(nvarchar(20),@wholePart) + '.' + substring(convert(varchar(50),ABS(checksum(@seed))),1,9));
end

select [AnotherWay] = [dbo].[GetId](@wholePart, newid()), * from [tblAttachments]</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/05/26/problems-with-floats-as-keys/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
