<?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; My Specific Situation</title>
	<atom:link href="http://www.elementalp.com/blog/index.php/category/my-specific-situation/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>Copy data from source db to target db avoiding tables with specific field names (used for MIP COFA conversion work)</title>
		<link>http://www.elementalp.com/blog/index.php/2015/09/03/copy-data-from-source-db-to-target-db-avoiding-tables-with-specific-field-names-used-for-mip-cofa-conversion-work/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/09/03/copy-data-from-source-db-to-target-db-avoiding-tables-with-specific-field-names-used-for-mip-cofa-conversion-work/#comments</comments>
		<pubDate>Thu, 03 Sep 2015 02:26:43 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[My Specific Situation]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=297</guid>
		<description><![CDATA[[crayon-6a06f75ce764e969849803/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">/*
 RUN THIS SCRIPT FROM THE *TARGET* DATABASE
 Copies table data from the @sourceDb database to the target database.
 Only tables that *do not* have segment code columns are copied.
 Optionally deletes the target table data if @deleteTargetData is set to 1
 */

 use [MyTargetDatabaseHere];
 declare @sourceDb nvarchar(255) = 'MySourceDatabaseHere';
 declare @deleteTargetData bit = 1;
 declare @message nvarchar(max) = null;

 begin try
         --disable triggers and constraints for target db
         exec sp_MSforeachtable 'alter table ? disable trigger all;
         alter table ? nocheck constraint all;'

         --create results temp table
         if (object_id('tempdb..#Results') is not null) drop table #Results
         create table #Results ([Name] nvarchar(1000), [Success] bit, [Error] nvarchar(max));

         --create #Table that contains the schema, table and column names of all tables in the database
         if (object_id('tempdb..#Tables') is not null) drop table #Tables

         select 
         [Table]
         ,[Schema]
         ,[Columns] = left([Columns],len(columns)-1) 
         ,[HasCodes] = convert(bit,case when charindex('sCodeID',[Columns], 1) &gt; 0 then 1 else 0 end)
         ,[HasIdentity] = [Identity].[HasIdentity]
         into #Tables
         from
         (
                 select top 10000 
                 [Table] = t.name
                 ,[TableObjectId] = t.object_id
                 ,[Schema] = s.[Name]
                 ,[Columns] = substring(
                 (
                 select
                 '[' + c.name + '], '
                 from sys.columns c 
                 where t.object_id = c.object_id
                 order by c.[Name]
                 for xml path('')
                 )
                 ,1,8000)
                 from sys.tables t
                 join sys.schemas s on t.[schema_id]= s.[schema_id]
                 where t.type = 'U'
                 order by t.name
         ) as f1
         outer apply(select top 1 [HasIdentity] = [is_identity] from sys.columns where object_id = f1.[TableObjectId]) as [Identity]
         where f1.[Table] not like 'sys%'
         group by [Table],[Schema],[Columns],[HasIdentity]
         order by [Schema],[Table]

         
         --create #NoCodeTables from #Table that contains only those tables that do not contain segment code columns
         if (object_id('tempdb..#NoCodeTables') is not null) drop table #NoCodeTables

         select *
         into #NoCodeTables
         from #Tables
         where [HasCodes] = 0

         select * from #NoCodeTables

         declare @table nvarchar(255)
         declare @schema nvarchar(255)
         declare @schemaAndTable nvarchar(1000)
         declare @columns nvarchar(max)
         declare @hasIdentity bit
         declare @sql nvarchar(max)

         --iterate the #NoCodeTables rows and do the copying
         while(1=1)
         begin
                 set @table = null;
                 set @sql = null;
                 set @message = null;

                 --get a row to process from #NoCodeTables
                 select top 1
                 @table = [Table]
                 ,@schema = [Schema]
                 ,@columns = [Columns]
                 ,@hasIdentity = [HasIdentity]
                 ,@schemaAndTable = '[' + @schema + '].[' + @table + ']' --combine schema and table names here for convenience
                 from #NoCodeTables
                 order by [Table],[Schema]

                 if(@table is not null)
                 begin
                         begin try
                                 --optionally delete the target table data
                                 if(@deleteTargetData = 1)
                                 begin
                                         --if a truncate doesn't work then fall back to a delete
                                         set @message = @schemaAndTable + ' emptying...'
                                         raiserror (@message, 0, 1) with nowait --print immediately

                                         set @sql = 'begin try
                                                 truncate table ' + @schemaAndTable + ';
                                         end try
                                         begin catch
                                                 delete ' + @schemaAndTable + ';
                                         end catch';

                                         exec (@sql);
                                 end

                                 --copy from source to target table
                                 set @message = @schemaAndTable + ' copying...'
                                 raiserror (@message, 0, 1) with nowait --print immediately

                                 --some tables have identity columns, if so, set to allow copying first
                                 set @sql = 
                                         case when @hasIdentity = 1 then 'SET IDENTITY_INSERT [' + @table + '] ON;' else '' end +
                                         'insert ' + @schemaAndTable + ' (' + @columns + ') select ' + @columns + ' from [' + @sourceDb + '].' + @schemaAndTable + ';' + 
                                         case when @hasIdentity = 1 then 'SET IDENTITY_INSERT [' + @table + '] OFF;' else '' end
                         
                                 --print @sql
                                 exec(@sql);

                                 --success! set messages
                                 set @message = @schemaAndTable + ' done.'
                                 insert #Results ([Name],[Success]) values (@schemaAndTable, 1) --insert
                                 raiserror (@message, 0, 1) with nowait --print immediately
                         end try
                         begin catch
                                 --fail. set message
                                 set @message = @schemaAndTable + ' copy FAILED.' + error_message()
                                 insert #Results ([Name],[Success],[Error]) values (@schemaAndTable, 0, @message)
                                 raiserror (@message, 0, 1) with nowait --print immediately
                         end catch

                         --delete the completed row from #NoCodeTables in preparation to move on to the next one
                         delete from #NoCodeTables where [Table] = @table        
                 end
                 else break; --all #NoCodeTables rows have been processed, break out of the loop
         end

         --display results
         select * 
         from #Results
         order by [Name]

 end try
 begin catch
         --error of some kind, print it and re-enable triggers and constraints (which may fail if a partial copy situation)
         set @message = error_message()
         raiserror (@message, 0, 1) with nowait --print immediately

         --enable triggers and constraints for target db
         exec sp_MSforeachtable 'alter table ? enable trigger all;
         alter table ? check constraint all;'

 end catch</pre><p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/09/03/copy-data-from-source-db-to-target-db-avoiding-tables-with-specific-field-names-used-for-mip-cofa-conversion-work/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find definitions and references of SQL Command Variables in a SQL script</title>
		<link>http://www.elementalp.com/blog/index.php/2015/07/23/find-definitions-and-references-of-sql-command-variables-in-a-sql-script/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/07/23/find-definitions-and-references-of-sql-command-variables-in-a-sql-script/#comments</comments>
		<pubDate>Thu, 23 Jul 2015 18:34:29 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[My Specific Situation]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=285</guid>
		<description><![CDATA[(This is a C# LinqPad script) Using setvar in T-SQL Finds the SQL Command Variable definitions in a SQL script and parses their names and values. Finds the SQL Command Variable references and parses their names. Determines which references have no definitions. Determines which definitions have no references. The definition names and reference names are [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>(This is a C# LinqPad script)</p>
<p><a href="http://www.elementalp.com/blog/index.php/2015/06/24/sql-cmd/"><span style="color: #0066cc;">Using setvar in T-SQL </span></a></p>
<p>Finds the SQL Command Variable definitions in a SQL script and parses their names and values.<br />
Finds the SQL Command Variable references and parses their names.<br />
Determines which references have no definitions.<br />
Determines which definitions have no references.</p>
<p>The definition names and reference names are case insensitive.<br />
A definition is in the form of :setvar name &#8220;value&#8221;<br />
A reference is in the form of $(name)</p><pre class="crayon-plain-tag">void Main()
{
	//sql file path
	string file = @"C:\temp\my.sql";
	
	//Token definition pattern for :setvar name "value"
	string tokenDefPattern = @"(\:setvar [^""]* ""[^""]*"")";
	string tokenDefNamePattern = @"\:setvar ([^ ""]*)";
	string tokenDefValuePattern = @"""([^""]*)""";	
	
	//Token reference pattern for $(name)
	string tokenRefPattern = @"(\$\([^)]*\))";
	string tokenRefNamePattern = @"\$\(([^)]*)\)";
	
	string text = System.IO.File.ReadAllText(file);
	
	var tokenDefs = Token.GetAllFirstCapturedMatches(text,tokenDefPattern).Distinct().ToDictionary(x=&gt;x,y=&gt;new Token(y,tokenDefNamePattern,tokenDefValuePattern));
	var tokenRefs = Token.GetAllFirstCapturedMatches(text,tokenRefPattern).Distinct().ToDictionary(x=&gt;x,y=&gt;new Token(y,tokenRefNamePattern,null));
	
	tokenDefs.Select(x=&gt;x.Value).OrderBy (x =&gt; x.Name).ToList().Dump("Token Definitions");
	tokenDefs.Where(x=&gt; !tokenRefs.Any(y =&gt; y.Value.Name == x.Value.Name)).Select(x=&gt;x.Value).OrderBy(x =&gt; x.Name).ToList().Dump("Token definitions without a reference");
	tokenRefs.Where(x=&gt; !tokenDefs.Any(y =&gt; y.Value.Name == x.Value.Name)).Select(x=&gt;x.Value).OrderBy(x =&gt; x.Name).ToList().Dump("Token references without a definition");
}

public class Token
{
	public Token(){}
	
	public Token(string Raw, string namePattern, string  valuePattern)
	{
		this.Raw = Raw;
		if(!string.IsNullOrWhiteSpace(namePattern)) Name = Token.GetFirstCapturedMatch(Raw,namePattern);
		if(!string.IsNullOrWhiteSpace(valuePattern)) Value = Token.GetFirstCapturedMatch(Raw,valuePattern);
	}

	public string Name {get;set;}
	public string Value {get;set;}
	public string Raw {get;set;}
	
	public static string GetFirstCapturedMatch(string value, string pattern)
	{
		var match = Regex.Match(value,pattern);
		if(match!=null &amp;&amp; match.Success &amp;&amp; match.Groups.Count&gt;1)
		{
			return match.Groups[1].Value;
		}
		return null;
	}
	
	public static List&lt;string&gt; GetAllFirstCapturedMatches(string value, string pattern)
	{
		var list = new List&lt;string&gt;();
		var matches = Regex.Matches(value,pattern);
		foreach(Match match in matches)
		{
			if(match!=null &amp;&amp; match.Success &amp;&amp; match.Groups.Count&gt;1) 
			{
				list.Add(match.Groups[1].Value);
			}
		}
		return list;
	}
}</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/07/23/find-definitions-and-references-of-sql-command-variables-in-a-sql-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Make duplicated [Order] values distinct</title>
		<link>http://www.elementalp.com/blog/index.php/2015/07/21/make-duplicated-order-values-distinct/</link>
		<comments>http://www.elementalp.com/blog/index.php/2015/07/21/make-duplicated-order-values-distinct/#comments</comments>
		<pubDate>Tue, 21 Jul 2015 21:52:32 +0000</pubDate>
		<dc:creator><![CDATA[ЈЦЅГЇП €ΘΘΚ]]></dc:creator>
				<category><![CDATA[My Specific Situation]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.elementalp.com/blog/?p=278</guid>
		<description><![CDATA[Note: The [Order] field is not unique in the database. The [Namespace] field is for multi-tenancy support. Using setvar in T-SQL [crayon-6a06f75cefc53352435656/] &#160;]]></description>
				<content:encoded><![CDATA[<p>Note: The [Order] field is not unique in the database. The [Namespace] field is for multi-tenancy support.</p>
<p><a href="http://www.elementalp.com/blog/index.php/2015/06/24/sql-cmd/">Using setvar in T-SQL</a></p><pre class="crayon-plain-tag">:setvar NAMESPACE "demo"

--find records with duplicated [Order] values
SELECT 
[Duplicated Order Value] = count(*)
,[Namespace]
--,[Group_Id]
,[Order]
FROM [peeps].[FieldRegistration] --[FieldCaseManagement]
where [Namespace] = '$(NAMESPACE)'
group by       
[Namespace]
--,[Group_Id]
,[Order]
having count(*) > 1
order by 
--[Group_Id], 
[Order]

--update [Order] values
update peeps.[FieldRegistration] set [Order] = x2.[Row]
from
(
	select [Namespace],[Name],[Field_Id],[Row]
	from 
	(
		select
		f.[Name]
		,fr.[Field_Id]
		,fr.[Namespace]
		,fr.[Order]
		,[Row] = (row_number() over (partition by fr.[Namespace] order by fr.[Order],f.[Name]) + 8) -- the +8 is because there are nine system fields stored elsewhere (only for [FieldRegistration] table).
		from [peeps].[FieldRegistration] fr
		join [peeps].[Field] f on f.[Id] = fr.[Field_Id]
	) as x1
	where [Row] &lt;&gt; [Order]
) as x2
where peeps.[FieldRegistration].[Namespace] = x2.[Namespace] 
and peeps.[FieldRegistration].[Field_Id] = x2.[Field_Id]
and peeps.[FieldRegistration].[Namespace] = '$(NAMESPACE)'

--display results
select * from peeps.[FieldRegistration]
where [Namespace] = '$(NAMESPACE)'
order by [Namespace],[Order]</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.elementalp.com/blog/index.php/2015/07/21/make-duplicated-order-values-distinct/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
