<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://kb.crmtogether.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Crmtogetherkb</id>
	<title>Sage CRM Knowledge Base - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://kb.crmtogether.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Crmtogetherkb"/>
	<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Special:Contributions/Crmtogetherkb"/>
	<updated>2026-04-08T08:52:15Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.42.3</generator>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=290</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=290"/>
		<updated>2022-09-30T11:35:54Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
Example for the bcp above&lt;br /&gt;
&lt;br /&gt;
   BULK INSERT saminc.dbo.ARCSM&lt;br /&gt;
	FROM &#039;C:\temp\importfiles\ARCSM.dat&#039;&lt;br /&gt;
	WITH (&lt;br /&gt;
             ROWTERMINATOR = &#039;\n&#039;&lt;br /&gt;
		);&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
See Bulk import for details on importing this data&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
  select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
     communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
     comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
     cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
     and Comm_TargetListId is null&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
  DECLARE @Comm_SecTerr as INT;&lt;br /&gt;
  DECLARE @Comm_CommunicationID as INT;&lt;br /&gt;
  DECLARE @commCursor as CURSOR;&lt;br /&gt;
  SET @commCursor = CURSOR FOR&lt;br /&gt;
   select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
   FROM&lt;br /&gt;
    communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr &lt;br /&gt;
     and Comm_TargetListId is null; --Comm_TargetListId-no updates on emarketing items&lt;br /&gt;
  OPEN @commCursor;&lt;br /&gt;
  FETCH NEXT FROM @commCursor INTO @Comm_SecTerr,@Comm_CommunicationID;&lt;br /&gt;
  WHILE @@FETCH_STATUS = 0&lt;br /&gt;
  BEGIN&lt;br /&gt;
    update Communication&lt;br /&gt;
    set Comm_SecTerr=@Comm_SecTerr&lt;br /&gt;
      where&lt;br /&gt;
        Comm_CommunicationId=@Comm_CommunicationID&lt;br /&gt;
         --print &#039;update Communication set Comm_SecTerr=&#039;+cast(@Comm_SecTerr as VARCHAR (50)) +&#039; where Comm_CommunicationId=&#039;+cast(@Comm_CommunicationID as VARCHAR (50))&lt;br /&gt;
    FETCH NEXT FROM @commCursor INTO @Comm_SecTerr, @Comm_CommunicationID;&lt;br /&gt;
   END&lt;br /&gt;
  CLOSE @commCursor;&lt;br /&gt;
  DEALLOCATE @commCursor;&lt;br /&gt;
&lt;br /&gt;
**note that if there is no parent company there will be no update so you may need to change the query or provide a separate query to update any orphan records&lt;br /&gt;
&lt;br /&gt;
-----&lt;br /&gt;
get the TCPIP port&lt;br /&gt;
&lt;br /&gt;
USE master&lt;br /&gt;
GO&lt;br /&gt;
xp_readerrorlog 0, 1, N&#039;Server is listening on&#039;, N&#039;any&#039;, NULL, NULL, N&#039;asc&#039; &lt;br /&gt;
GO&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Self-Service&amp;diff=289</id>
		<title>Self-Service</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Self-Service&amp;diff=289"/>
		<updated>2021-01-12T15:58:32Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;CRM will only allow one instance per server of CRM be the self-service portal&lt;br /&gt;
&lt;br /&gt;
Troubleshoot&lt;br /&gt;
&lt;br /&gt;
To re-register the server open a command prompt and navigate to the wwwroot folder within the CRM folder structure. &lt;br /&gt;
Typically this is &#039;C:\Program Files\Sage\CRM\CRM\WWWRoot&#039;&lt;br /&gt;
Once there type&lt;br /&gt;
  regsvr32 eware.dll&lt;br /&gt;
&lt;br /&gt;
A Message should appear to confirm that the eware.dll has been registered.&lt;br /&gt;
Typically if this is required you will also need to reset the registry settings to point to the correct CRM database also.&lt;br /&gt;
&lt;br /&gt;
Self-Service check list&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
1. Registry&lt;br /&gt;
&lt;br /&gt;
  [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\eWare\SelfService]&lt;br /&gt;
  &amp;quot;SSDbDatabaseDriver&amp;quot;=&amp;quot;MSSQL&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbEntDatabaseDriver&amp;quot;=&amp;quot;MSSQL&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbDatabaseServer&amp;quot;=&amp;quot;servername\\crmsqlexpress&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbUserName&amp;quot;=&amp;quot;sa&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbEntDatabaseServer&amp;quot;=&amp;quot;servername\\crmsqlexpress&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbEntUser&amp;quot;=&amp;quot;sa&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbDatabaseName&amp;quot;=&amp;quot;CRMSelfService&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbEntDatabaseName&amp;quot;=&amp;quot;CRM&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbPassword&amp;quot;=&amp;quot;password&amp;quot;&lt;br /&gt;
  &amp;quot;SSDbEntPassword&amp;quot;=&amp;quot;password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
2. Database&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  --SQL to create the database&lt;br /&gt;
&lt;br /&gt;
  USE [master]&lt;br /&gt;
  GO&lt;br /&gt;
  CREATE DATABASE [CRMSelfService] ON  PRIMARY &lt;br /&gt;
  ( NAME = N&#039;CRMSelfService&#039;, FILENAME = N&#039;CRMSelfService.mdf&#039; , SIZE = 2304KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )&lt;br /&gt;
   LOG ON &lt;br /&gt;
   ( NAME = N&#039;CRMSelfService_log&#039;, FILENAME = N&#039;CRMSelfService_log.LDF&#039; , SIZE = 576KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)&lt;br /&gt;
  GO&lt;br /&gt;
  ALTER DATABASE [CRMSelfService] SET COMPATIBILITY_LEVEL = 100&lt;br /&gt;
  GO&lt;br /&gt;
  IF (1 = FULLTEXTSERVICEPROPERTY(&#039;IsFullTextInstalled&#039;))  &lt;br /&gt;
  begin&lt;br /&gt;
  EXEC [CRMSelfService].[dbo].[sp_fulltext_database] @action = &#039;enable&#039;&lt;br /&gt;
  end&lt;br /&gt;
  GO&lt;br /&gt;
  ALTER DATABASE [CRMSelfService] SET ANSI_NULL_DEFAULT OFF &lt;br /&gt;
  GO&lt;br /&gt;
  ALTER DATABASE [CRMSelfService] SET ANSI_NULLS OFF &lt;br /&gt;
  GO&lt;br /&gt;
  ALTER DATABASE [CRMSelfService] SET ANSI_PADDING OFF &lt;br /&gt;
  GO&lt;br /&gt;
  ALTER DATABASE [CRMSelfService] SET ANSI_WARNINGS OFF &lt;br /&gt;
  GO&lt;br /&gt;
  SET ANSI_NULLS ON&lt;br /&gt;
  GO&lt;br /&gt;
  SET QUOTED_IDENTIFIER ON&lt;br /&gt;
  GO&lt;br /&gt;
  CREATE TABLE [dbo].[Visitor](&lt;br /&gt;
	[Visi_VisitorId] [int] IDENTITY(1,1) NOT NULL,&lt;br /&gt;
	[Visi_VisitorKey] [nvarchar](50) NULL,&lt;br /&gt;
	[Visi_LogonId] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_Password] [nvarchar](12) NULL,&lt;br /&gt;
	[Visi_PersonId] [int] NULL,&lt;br /&gt;
	[Visi_CompanyId] [int] NULL,&lt;br /&gt;
	[Visi_IpAddress] [nvarchar](15) NULL,&lt;br /&gt;
	[Visi_Salutation] [nvarchar](10) NULL,&lt;br /&gt;
	[Visi_FirstName] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_LastName] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_MiddleName] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_Suffix] [nvarchar](20) NULL,&lt;br /&gt;
	[Visi_Gender] [nvarchar](6) NULL,&lt;br /&gt;
	[Visi_Title] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_TitleCode] [nvarchar](15) NULL,&lt;br /&gt;
	[Visi_CompanyName] [nvarchar](60) NULL,&lt;br /&gt;
	[Visi_PhoneCountryCode] [nvarchar](5) NULL,&lt;br /&gt;
	[Visi_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[Visi_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[Visi_FaxCountryCode] [nvarchar](5) NULL,&lt;br /&gt;
	[Visi_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[Visi_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[Visi_EmailAddress] [nvarchar](50) NULL,&lt;br /&gt;
	[Visi_Address1] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_Address2] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_Address3] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_Address4] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_Address5] [nvarchar](40) NULL,&lt;br /&gt;
	[Visi_City] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_State] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_Country] [nvarchar](30) NULL,&lt;br /&gt;
	[Visi_PostCode] [nvarchar](10) NULL,&lt;br /&gt;
	[Visi_Language] [nvarchar](5) NULL,&lt;br /&gt;
	[Visi_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[Visi_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[visi_userid] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  CREATE TABLE [dbo].[VisitorProfile](&lt;br /&gt;
	[Prof_ProfileId] [int] IDENTITY(1,1) NOT NULL,&lt;br /&gt;
	[Prof_VisitorID] [int] NULL,&lt;br /&gt;
	[Prof_ProfileType] [nvarchar](30) NULL,&lt;br /&gt;
	[Prof_Details] [nvarchar](120) NULL,&lt;br /&gt;
	[Prof_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[Prof_UpdatedDate] [datetime] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
3. Date format&lt;br /&gt;
&lt;br /&gt;
The customer wanted the dates within Self Service to be shown mm/dd/yyy.&lt;br /&gt;
&lt;br /&gt;
This can be accomplished by changing a value in the User Configuration area within the Administration screens.&lt;br /&gt;
Go to&lt;br /&gt;
&lt;br /&gt;
Administration → Users → User Configuration&lt;br /&gt;
&lt;br /&gt;
Change the field &amp;quot;Default user date format&amp;quot; to mm/dd/yyyy.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This will change all dates displayed in Self Service for all visitors (Authenticated and Anonymous).&lt;br /&gt;
&lt;br /&gt;
ref: https://www.sagecity.com/sage-global-solutions/sage-crm/b/sage-crm-hints-tips-and-tricks/posts/sage-crm-&lt;br /&gt;
2020-r1-controlling-the-date-display-format-in-self-service#:~:text=A%20customer%20had%20the%20requirement,format%20dd%2Fmm%2Fyyyy.&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=288</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=288"/>
		<updated>2020-02-22T22:47:34Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
Example for the bcp above&lt;br /&gt;
&lt;br /&gt;
   BULK INSERT saminc.dbo.ARCSM&lt;br /&gt;
	FROM &#039;C:\temp\importfiles\ARCSM.dat&#039;&lt;br /&gt;
	WITH (&lt;br /&gt;
             ROWTERMINATOR = &#039;\n&#039;&lt;br /&gt;
		);&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
See Bulk import for details on importing this data&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
  select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
     communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
     comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
     cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
     and Comm_TargetListId is null&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
  DECLARE @Comm_SecTerr as INT;&lt;br /&gt;
  DECLARE @Comm_CommunicationID as INT;&lt;br /&gt;
  DECLARE @commCursor as CURSOR;&lt;br /&gt;
  SET @commCursor = CURSOR FOR&lt;br /&gt;
   select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
   FROM&lt;br /&gt;
    communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr &lt;br /&gt;
     and Comm_TargetListId is null; --Comm_TargetListId-no updates on emarketing items&lt;br /&gt;
  OPEN @commCursor;&lt;br /&gt;
  FETCH NEXT FROM @commCursor INTO @Comm_SecTerr,@Comm_CommunicationID;&lt;br /&gt;
  WHILE @@FETCH_STATUS = 0&lt;br /&gt;
  BEGIN&lt;br /&gt;
    update Communication&lt;br /&gt;
    set Comm_SecTerr=@Comm_SecTerr&lt;br /&gt;
      where&lt;br /&gt;
        Comm_CommunicationId=@Comm_CommunicationID&lt;br /&gt;
         --print &#039;update Communication set Comm_SecTerr=&#039;+cast(@Comm_SecTerr as VARCHAR (50)) +&#039; where Comm_CommunicationId=&#039;+cast(@Comm_CommunicationID as VARCHAR (50))&lt;br /&gt;
    FETCH NEXT FROM @commCursor INTO @Comm_SecTerr, @Comm_CommunicationID;&lt;br /&gt;
   END&lt;br /&gt;
  CLOSE @commCursor;&lt;br /&gt;
  DEALLOCATE @commCursor;&lt;br /&gt;
&lt;br /&gt;
**note that if there is no parent company there will be no update so you may need to change the query or provide a separate query to update any orphan records&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=287</id>
		<title>Screen Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=287"/>
		<updated>2018-08-29T15:59:55Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
To add in script code from a page set the link as follows&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;script src=&amp;quot;../custompages/pathtofile/commlist.js&amp;quot; type=&amp;quot;text/javascript&amp;quot; language=&amp;quot;JavaScript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To enumerate block entries (Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/11/28/setting-screen-properties-within-a-multiblock-asp-page-using-the-com-api.aspx)&lt;br /&gt;
&lt;br /&gt;
  //Set EntryBlock properties for an EntryGroup Block using an Enumerator&lt;br /&gt;
  var myE = new Enumerator(myBlock);&lt;br /&gt;
  while (!myE.atEnd())&lt;br /&gt;
  {&lt;br /&gt;
     myEntryBlock = myE.item();&lt;br /&gt;
     myEntryBlock.ReadOnly = false;&lt;br /&gt;
     myEntryBlock.Required = false;&lt;br /&gt;
     myE.moveNext();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Useful menthod to parse the querystring from the client&lt;br /&gt;
&lt;br /&gt;
Ref: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx&lt;br /&gt;
&lt;br /&gt;
  function getQuerystring(key, default_)&lt;br /&gt;
  {&lt;br /&gt;
    if (default_==null) default_=&amp;quot;&amp;quot;;&lt;br /&gt;
    key = key.replace(/[\[]/,&amp;quot;\\\[&amp;quot;).replace(/[\]]/,&amp;quot;\\\]&amp;quot;);&lt;br /&gt;
    var regex = new RegExp(&amp;quot;[\\?&amp;amp;]&amp;quot;+key+&amp;quot;=([^&amp;amp;#]*)&amp;quot;);&lt;br /&gt;
    var qs = regex.exec(window.location.href);&lt;br /&gt;
    if(qs == null)&lt;br /&gt;
      return default_;&lt;br /&gt;
    else&lt;br /&gt;
      return qs[1];&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To break up a screen visually create a dummy field and add in&lt;br /&gt;
&lt;br /&gt;
  &amp;amp;lt;HR border=1&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
as the caption&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Adding new phone and email addresses to screens&lt;br /&gt;
&lt;br /&gt;
Go into translations and look up Link_CompPhon (or link_prefixphone/email)&lt;br /&gt;
&lt;br /&gt;
This shows you a list which you can add to by adding new translations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Custom validation on a screen&lt;br /&gt;
&lt;br /&gt;
If you have a custom method for validating data and you wish to code this in your ASP page (or outside of the validation script area) then you need to do something like the following&lt;br /&gt;
&lt;br /&gt;
  Entry = ctproductblock.GetEntry(&amp;quot;productname&amp;quot;);&lt;br /&gt;
  if(!validate(Request.Form(&amp;quot;productcode&amp;quot;)))&lt;br /&gt;
  {					&lt;br /&gt;
      Entry.ValidateScript = &amp;quot;Valid=false;ErrorStr=&#039;Product code already exists&#039;;&amp;quot;; &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
if our sample above the validate() method checks that the product code is unique.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/07/22/server-side-validation-and-asp-pages.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Add a hyper link to a field on a screen - Custom SSA fields can only be hyperlinked throught the UI for lists and not for screens so here we have a workaround.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2010/07/06/hyperlinking-to-a-parent-custom-entity-from-a-search-select-advanced-field.aspx&lt;br /&gt;
&lt;br /&gt;
*Within CRM open the screen&lt;br /&gt;
*Select the field&lt;br /&gt;
*Within the &amp;quot;create script&amp;quot; textbox enter in the following (update as per your custom entity first)&lt;br /&gt;
&lt;br /&gt;
  var intRecordId = CRM.GetContextInfo(&amp;quot;opportunity&amp;quot;,&amp;quot;oppo_projectid&amp;quot;);&lt;br /&gt;
  var strURL = CRM.URL(&amp;quot;project/projectsummary.asp&amp;quot;)+&amp;quot;&amp;amp;proj_projectid=&amp;quot;+intRecordId;&lt;br /&gt;
  var strCaptionText = &amp;quot;Project&amp;quot;;&lt;br /&gt;
  var strFullCaption = &amp;quot;&amp;lt;a href=&amp;quot;+strURL+&amp;quot;&amp;gt;&amp;quot;+strCaptionText+&amp;quot;&amp;lt;/a&amp;gt;:&amp;quot;;&lt;br /&gt;
  Caption = strFullCaption;&lt;br /&gt;
&lt;br /&gt;
This sets the field &amp;quot;Caption&amp;quot; to be a hyperlink so it is not ideal but works as a quick &amp;quot;fix&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Field Validate scripts - Values vs values - (seen in 7.1)&lt;br /&gt;
&lt;br /&gt;
This threw me a few times....within field validate scripts the &amp;quot;values&amp;quot; object starts with a lowercase v&lt;br /&gt;
&lt;br /&gt;
  ErrorStr=&amp;quot;testx=&amp;quot;+values(&amp;quot;case_ct_supportemail&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Anything in values only comes from the screen so if the field referenced is not on the screen then it wont be in values - you would then query the db to get that value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Ajax Request&lt;br /&gt;
&lt;br /&gt;
function _makeRequestGET(path, callback)&lt;br /&gt;
{&lt;br /&gt;
  _dbg(&amp;quot;_makeRequestGET path:&amp;quot;+path);&lt;br /&gt;
  &lt;br /&gt;
    $.ajax({&lt;br /&gt;
        type: &amp;quot;Get&amp;quot;,&lt;br /&gt;
        url: path,&lt;br /&gt;
        success: function (data, text) {&lt;br /&gt;
            callback(data);&lt;br /&gt;
        },&lt;br /&gt;
        error: function (request, status, error) {&lt;br /&gt;
            alert(&amp;quot;ERROR in _makeRequestGET: &amp;quot;+request + &amp;quot; status:&amp;quot;+ status + &amp;quot; path:&amp;quot;+ path);&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
}&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=286</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=286"/>
		<updated>2017-06-23T14:36:12Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
  select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
     communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
     comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
     cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
     and Comm_TargetListId is null&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
  DECLARE @Comm_SecTerr as INT;&lt;br /&gt;
  DECLARE @Comm_CommunicationID as INT;&lt;br /&gt;
  DECLARE @commCursor as CURSOR;&lt;br /&gt;
  SET @commCursor = CURSOR FOR&lt;br /&gt;
   select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
   FROM&lt;br /&gt;
    communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr &lt;br /&gt;
     and Comm_TargetListId is null; --Comm_TargetListId-no updates on emarketing items&lt;br /&gt;
  OPEN @commCursor;&lt;br /&gt;
  FETCH NEXT FROM @commCursor INTO @Comm_SecTerr,@Comm_CommunicationID;&lt;br /&gt;
  WHILE @@FETCH_STATUS = 0&lt;br /&gt;
  BEGIN&lt;br /&gt;
    update Communication&lt;br /&gt;
    set Comm_SecTerr=@Comm_SecTerr&lt;br /&gt;
      where&lt;br /&gt;
        Comm_CommunicationId=@Comm_CommunicationID&lt;br /&gt;
         --print &#039;update Communication set Comm_SecTerr=&#039;+cast(@Comm_SecTerr as VARCHAR (50)) +&#039; where Comm_CommunicationId=&#039;+cast(@Comm_CommunicationID as VARCHAR (50))&lt;br /&gt;
    FETCH NEXT FROM @commCursor INTO @Comm_SecTerr, @Comm_CommunicationID;&lt;br /&gt;
   END&lt;br /&gt;
  CLOSE @commCursor;&lt;br /&gt;
  DEALLOCATE @commCursor;&lt;br /&gt;
&lt;br /&gt;
**note that if there is no parent company there will be no update so you may need to change the query or provide a separate query to update any orphan records&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=285</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=285"/>
		<updated>2017-06-23T14:35:47Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
  select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
     communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
     comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
     cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
     and Comm_TargetListId is null&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
  DECLARE @Comm_SecTerr as INT;&lt;br /&gt;
  DECLARE @Comm_CommunicationID as INT;&lt;br /&gt;
  DECLARE @commCursor as CURSOR;&lt;br /&gt;
  SET @commCursor = CURSOR FOR&lt;br /&gt;
   select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
   FROM&lt;br /&gt;
    communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
	 and Comm_TargetListId is null; --Comm_TargetListId-no updates on emarketing items&lt;br /&gt;
  OPEN @commCursor;&lt;br /&gt;
  FETCH NEXT FROM @commCursor INTO @Comm_SecTerr,@Comm_CommunicationID;&lt;br /&gt;
  WHILE @@FETCH_STATUS = 0&lt;br /&gt;
  BEGIN&lt;br /&gt;
    update Communication&lt;br /&gt;
    set Comm_SecTerr=@Comm_SecTerr&lt;br /&gt;
      where&lt;br /&gt;
        Comm_CommunicationId=@Comm_CommunicationID&lt;br /&gt;
         --print &#039;update Communication set Comm_SecTerr=&#039;+cast(@Comm_SecTerr as VARCHAR (50)) +&#039; where Comm_CommunicationId=&#039;+cast(@Comm_CommunicationID as VARCHAR (50))&lt;br /&gt;
    FETCH NEXT FROM @commCursor INTO @Comm_SecTerr, @Comm_CommunicationID;&lt;br /&gt;
   END&lt;br /&gt;
  CLOSE @commCursor;&lt;br /&gt;
  DEALLOCATE @commCursor;&lt;br /&gt;
&lt;br /&gt;
**note that if there is no parent company there will be no update so you may need to change the query or provide a separate query to update any orphan records&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=284</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=284"/>
		<updated>2017-06-23T14:34:33Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
   communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
	 and Comm_TargetListId is null&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
 DECLARE @Comm_SecTerr as INT;&lt;br /&gt;
DECLARE @Comm_CommunicationID as INT;&lt;br /&gt;
&lt;br /&gt;
DECLARE @commCursor as CURSOR;&lt;br /&gt;
 &lt;br /&gt;
SET @commCursor = CURSOR FOR&lt;br /&gt;
 select comp.Comp_SecTerr,comm.Comm_CommunicationID&lt;br /&gt;
  FROM&lt;br /&gt;
   communication comm, company comp, Comm_Link cmli&lt;br /&gt;
  where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
     and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
	 and Comm_TargetListId is null; --Comm_TargetListId-no updates on emarketing items&lt;br /&gt;
&lt;br /&gt;
OPEN @commCursor;&lt;br /&gt;
FETCH NEXT FROM @commCursor INTO @Comm_SecTerr,@Comm_CommunicationID;&lt;br /&gt;
 &lt;br /&gt;
WHILE @@FETCH_STATUS = 0&lt;br /&gt;
BEGIN&lt;br /&gt;
 update Communication&lt;br /&gt;
 set Comm_SecTerr=@Comm_SecTerr&lt;br /&gt;
 where&lt;br /&gt;
 Comm_CommunicationId=@Comm_CommunicationID&lt;br /&gt;
 --print &#039;update Communication set Comm_SecTerr=&#039;+cast(@Comm_SecTerr as VARCHAR (50)) +&#039; where Comm_CommunicationId=&#039;+cast(@Comm_CommunicationID as VARCHAR (50))&lt;br /&gt;
 FETCH NEXT FROM @commCursor INTO @Comm_SecTerr, @Comm_CommunicationID;&lt;br /&gt;
END&lt;br /&gt;
 &lt;br /&gt;
CLOSE @commCursor;&lt;br /&gt;
DEALLOCATE @commCursor;&lt;br /&gt;
&lt;br /&gt;
**note that if there is no parent company there will be no update so you may need to change the query or provide a separate query to update any orphan records&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=283</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=283"/>
		<updated>2017-06-22T10:19:07Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Updating (fixing) Territories&lt;br /&gt;
&lt;br /&gt;
The select statement below should return all communication records that don&#039;t match the parent company&lt;br /&gt;
&lt;br /&gt;
  select Comm_SecTerr, Comp_SecTerr,comp_name,comm.*&lt;br /&gt;
   FROM&lt;br /&gt;
   communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
    comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
    cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
    and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;br /&gt;
&lt;br /&gt;
To get these communications to match run the following SQL&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
   communication&lt;br /&gt;
  SET&lt;br /&gt;
    communication.Comm_SecTerr=comp.comp_secterr&lt;br /&gt;
   FROM&lt;br /&gt;
    communication comm, company comp, Comm_Link cmli&lt;br /&gt;
   where &lt;br /&gt;
     comm.Comm_CommunicationID = cmli.CmLi_Comm_CommunicationID and&lt;br /&gt;
     cmli.CmLi_Comm_CompanyID=comp.Comp_CompanyId&lt;br /&gt;
      and comm.Comm_SecTerr&amp;lt;&amp;gt;comp.Comp_SecTerr&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=282</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=282"/>
		<updated>2017-06-08T10:11:41Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Refresh views in a database. Useful for random SQL errors that have nothing in the log for them.&lt;br /&gt;
&lt;br /&gt;
  DECLARE @sqlcmd NVARCHAR(MAX) = &#039;&#039;&lt;br /&gt;
  SELECT @sqlcmd = @sqlcmd +  &#039;EXEC sp_refreshview &#039;&#039;&#039; + name + &#039;&#039;&#039;;&#039; &lt;br /&gt;
  FROM sys.objects AS so  &lt;br /&gt;
  WHERE so.type = &#039;V&#039; &lt;br /&gt;
  SELECT @sqlcmd&lt;br /&gt;
  --EXEC(@sqlcmd)&lt;br /&gt;
&lt;br /&gt;
ref: http://www.sqlservercentral.com/scripts/Views/147316/&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=ASP&amp;diff=281</id>
		<title>ASP</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=ASP&amp;diff=281"/>
		<updated>2017-06-01T10:25:21Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Cannot see the error messages in IIS&lt;br /&gt;
&lt;br /&gt;
  You can configure these settings by using IIS Manager. To do so, open IIS Manager and navigate to the site or application where you want to enable or disable script messages, and then double-click the ASP feature.&lt;br /&gt;
&lt;br /&gt;
  In the list of ASP features, configure the Script Error Message and Send Errors To Browser options.&lt;br /&gt;
&lt;br /&gt;
Ref: http://learn.iis.net/page.aspx/564/classic-asp-script-error-messages-no-longer-shown-in-web-browser-by-default/&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Cannot create automation object - Issue caused by the eware.dll not being registered correctly&lt;br /&gt;
&lt;br /&gt;
Instruction to manually swap in a new eware.dll&lt;br /&gt;
&lt;br /&gt;
    #Stop the IIS server.&lt;br /&gt;
    #Backup the existing CRM eWare.dll and database, rename the eWare.dll file.&lt;br /&gt;
    #Copy the interim patch eWare.dll to the CRM directory.&lt;br /&gt;
    #Register the new eWare.dll by using regsvr32.exe.e.g. regsvr32 &amp;quot;C:\Program Files\Sage\CRM\\WWWRoot\eWare.dll&amp;quot;&lt;br /&gt;
    #Restart the IIS server. &lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2008/02/06/patches-and-service-packs-and-registering-the-eware-dll.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Nice details here on how to use security in ASP pages&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2009/02/10/more-about-using-crm-security-in-asp-pages.aspx&lt;br /&gt;
&lt;br /&gt;
Basically you use the CRM.Button API&lt;br /&gt;
&lt;br /&gt;
  if (!CRM.Button(&amp;quot;caption&amp;quot;,&amp;quot;image.gif&amp;quot;, &amp;quot;url.asp&amp;quot;,&amp;quot;COMPANY&amp;quot;,&amp;quot;EDIT&amp;quot;)) &lt;br /&gt;
  {&lt;br /&gt;
    ...so something&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Parameters 	&lt;br /&gt;
&lt;br /&gt;
1. Caption: The caption for the button. This is translated based on the user&#039;s language (providing there is a matching entry in CRM Translations).&lt;br /&gt;
&lt;br /&gt;
2. ImageName: The image you want displayed on the button. All images need to be stored in the CRM directory &#039;Img&#039; folder.&lt;br /&gt;
&lt;br /&gt;
3. URL: The URL that this button links to. This can either be a link to a Web address or to a custom page in the CRM custom pages folder. (See URL below).&lt;br /&gt;
&lt;br /&gt;
4. PermissionsEntity: PermissionsEntity is the name of the entity. &lt;br /&gt;
&lt;br /&gt;
5. PermissionsType is either VIEW, EDIT, DELETE or INSERT, depending on the action of the button.&lt;br /&gt;
&lt;br /&gt;
6. Target: This allows the TARGET property of the button&#039;s anchor () tag to be set. &lt;br /&gt;
&lt;br /&gt;
API Ref: https://community.sagecrm.com/developerhelp/Content/Developer/ASP%20Object%20Reference/CRMBase%20Object/AS_CRMBaseButton.htm?SearchType=Stem&amp;amp;Highlight=buttons|Button|button|Buttons&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
To Enumerate the columns in a crm record object you can do the following:&lt;br /&gt;
&lt;br /&gt;
  var myE = new Enumerator(recordObj);	&lt;br /&gt;
  while (!myE.atEnd()) {&lt;br /&gt;
    var nm=myE.item();&lt;br /&gt;
    //...do seomthing&lt;br /&gt;
    myE.moveNext();  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to sent a message and create a communicationn in CRM&lt;br /&gt;
&lt;br /&gt;
  var myMailObject = CRM.GetBlock(&amp;quot;Messageblock&amp;quot;); &lt;br /&gt;
  with (myMailObject){ &lt;br /&gt;
  DisplayForm = false; &lt;br /&gt;
  var strEmailId=new String(ctQueueRec.ctqu_data1); &lt;br /&gt;
  if(strEmailId==&amp;quot;&amp;quot; || strEmailId==&amp;quot;undefined&amp;quot;)strEmailId=&amp;quot;&amp;quot;; &lt;br /&gt;
  if(strEmailId!=&amp;quot;&amp;quot;){ &lt;br /&gt;
  var strSubject=new String(ctQueueRec.ctqu_data2); &lt;br /&gt;
  if(strSubject==&amp;quot;&amp;quot; || strSubject==&amp;quot;undefined&amp;quot;)strSubject=&amp;quot;&amp;quot;; &lt;br /&gt;
  var strBody=new String(ctQueueRec.ctqu_data3); &lt;br /&gt;
  if(strBody==&amp;quot;&amp;quot; || strBody==&amp;quot;undefined&amp;quot;)strBody=&amp;quot;&amp;quot;; &lt;br /&gt;
  mSubject =strSubject; &lt;br /&gt;
  mBody =strBody;  &lt;br /&gt;
  AddRecipient(strEmailId,strEmailId,&amp;quot;TO&amp;quot;); &lt;br /&gt;
  Mode = 2; &lt;br /&gt;
  //CRM.AddContent(myMailObject.execute());  &lt;br /&gt;
  if (true){ &lt;br /&gt;
&lt;br /&gt;
    var RecordComm = CRM.CreateRecord(&amp;quot;Communication&amp;quot;); &lt;br /&gt;
    RecordComm.comm_action=&amp;quot;EmailOut&amp;quot;; &lt;br /&gt;
    RecordComm.comm_status=&amp;quot;Complete&amp;quot;; &lt;br /&gt;
    RecordComm.comm_priority=&amp;quot;Normal&amp;quot;; &lt;br /&gt;
    RecordComm.comm_type=&amp;quot;Task&amp;quot;; &lt;br /&gt;
    RecordComm.comm_to=strEmailId; &lt;br /&gt;
    RecordComm.comm_email=strBody; &lt;br /&gt;
    RecordComm.comm_subject=strSubject; &lt;br /&gt;
    RecordComm.comm_note=strSubject; &lt;br /&gt;
    RecordComm.comm_datetime=executiondate.getVarDate();; &lt;br /&gt;
    RecordComm.SaveChanges(); &lt;br /&gt;
    var RecordComm_Link = CRM.CreateRecord(&amp;quot;Comm_Link&amp;quot;); &lt;br /&gt;
    RecordComm_Link.CmLi_Comm_CommunicationId=RecordComm.comm_communicationid; &lt;br /&gt;
    RecordComm_Link.CmLi_Comm_UserId=1; &lt;br /&gt;
    var ipersonId=new String(ctQueueRec.ctqu_data4); &lt;br /&gt;
    if(ipersonId==&amp;quot;&amp;quot; || ipersonId==&amp;quot;undefined&amp;quot;)ipersonId=0; &lt;br /&gt;
    if(ipersonId!=0) &lt;br /&gt;
       RecordComm_Link.CmLi_Comm_PersonId=ipersonId; &lt;br /&gt;
    //RecordComm_Link.cmli_comm_companyid=strCompanyId; &lt;br /&gt;
    RecordComm_Link.SaveChanges(); &lt;br /&gt;
    Response.Write(&amp;quot;done&amp;quot;+ipersonId); &lt;br /&gt;
    } &lt;br /&gt;
    else{ &lt;br /&gt;
        Response.Write(&amp;quot;There has been a problem: &amp;quot;+mErrorMessage); &lt;br /&gt;
    } &lt;br /&gt;
    } &lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
800ffff error on pages&lt;br /&gt;
&lt;br /&gt;
This is a CRM issue and you need to restart the server to resolve this&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=280</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=280"/>
		<updated>2017-02-22T10:20:57Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to reset admin password and remove lockout&lt;br /&gt;
&lt;br /&gt;
  update Users&lt;br /&gt;
    set User_Password=&#039;&#039;,&lt;br /&gt;
    user_accountlockedout=null&lt;br /&gt;
    where User_Logon=&#039;admin&#039;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Troubleshoot&amp;diff=279</id>
		<title>Troubleshoot</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Troubleshoot&amp;diff=279"/>
		<updated>2017-01-03T11:03:14Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This seciton is for CRM Together staff to help troubleshoot product installs&lt;br /&gt;
&lt;br /&gt;
1. Client toolbar only half lights up and Outlook when starting always asks to reconnect to CRM.&lt;br /&gt;
&lt;br /&gt;
Check the Server error log. &lt;br /&gt;
If you see 500 errors there is a chance that the server request (which is made within the iis process) is not allowed and so is returning 500 errors. &lt;br /&gt;
&lt;br /&gt;
To resolve this open the web.config file and set the CRMCodedPath setting to be something like &amp;quot;http://servername/CRM/&amp;quot;. (Note: you may need to add this setting)&lt;br /&gt;
&lt;br /&gt;
For example&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!--&lt;br /&gt;
    //Coded path to be used when external only ip address might be used blocking titan from talking to asp bridge&lt;br /&gt;
    //also requires CRM setting IPAddressChecking to be disabled&lt;br /&gt;
    --&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMCodedPath&amp;quot; value=&amp;quot;http://localhost/crm/&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This can happen to any application written in Titan so this applies to all products.&lt;br /&gt;
&lt;br /&gt;
2. NT Authenication Error&lt;br /&gt;
&lt;br /&gt;
Depending on the IIS setup you may need to add in a windows users details to the web.config file. This usually occurs when IIS requires authentication.&lt;br /&gt;
&lt;br /&gt;
Set the following values to be a relevenat user. It is best to ensure that the users password does not expire.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkUser&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkUserPassword&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkDomain&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
(Note: you may need to add these settings)&lt;br /&gt;
&lt;br /&gt;
3. Fiddler is a great tool for debugging HTTP requests.&lt;br /&gt;
&lt;br /&gt;
One thing to remember is..&lt;br /&gt;
&lt;br /&gt;
Important: Regardless of other settings, .NET will always bypass the Fiddler proxy for URLs containing localhost.  So, rather than using localhost, change your code to refer to the machine name.  For instance:&lt;br /&gt;
&lt;br /&gt;
    Does not show in Fiddler: http://localhost/X509SignCodeService/X509SigningService.asmx&lt;br /&gt;
&lt;br /&gt;
    Shows in Fiddler: http://mymachine/X509SignCodeService/X509SigningService.asmx&lt;br /&gt;
&lt;br /&gt;
4. Parameter name cannot be zero&lt;br /&gt;
&lt;br /&gt;
This is an error on the Accelerator license. Something has changed or broken the license.&lt;br /&gt;
Should be fixed in an upcoming release (after Jan 2012)&lt;br /&gt;
&lt;br /&gt;
5. 500.21 (pagehandlerfactory integrated has a Bad Module)&lt;br /&gt;
&lt;br /&gt;
http://blogs.microsoft.co.il/blogs/gadib/archive/2010/10/26/iis-error-handler-pagehandlerfactory-integrated-has-a-bad-module-managedpipelinehandler-in-its-moudle-list.aspx&lt;br /&gt;
&lt;br /&gt;
it seems .net 4.0 might not be installed .&lt;br /&gt;
&lt;br /&gt;
see also&lt;br /&gt;
&lt;br /&gt;
http://www.compdigitec.com/labs/2010/07/12/solving-handler-pagehandlerfactory-integrated-has-a-bad-module-managedpipelinehandler-in-asp-net-4-0/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Class not registered, ClassID: {7C6E29BC-8B8B-4C3D-859E-AF6CD158BE0F} &lt;br /&gt;
&lt;br /&gt;
The issue here is that the &lt;br /&gt;
&lt;br /&gt;
   MSXML 4.0 parser&lt;br /&gt;
&lt;br /&gt;
component is missing and this is used by SOAP to connect to the CRM web services&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Folder could not be created: &amp;quot;C:\Program Files (x86)\Sage\CRM\CRM\Library\S\Some Company&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The issue is that the IUSR account has not got permissions to create this folder.&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Troubleshoot&amp;diff=278</id>
		<title>Troubleshoot</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Troubleshoot&amp;diff=278"/>
		<updated>2017-01-03T11:01:52Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This seciton is for CRM Together staff to help troubleshoot product installs&lt;br /&gt;
&lt;br /&gt;
1. Client toolbar only half lights up and Outlook when starting always asks to reconnect to CRM.&lt;br /&gt;
&lt;br /&gt;
Check the Server error log. &lt;br /&gt;
If you see 500 errors there is a chance that the server request (which is made within the iis process) is not allowed and so is returning 500 errors. &lt;br /&gt;
&lt;br /&gt;
To resolve this open the web.config file and set the CRMCodedPath setting to be something like &amp;quot;http://servername/CRM/&amp;quot;. (Note: you may need to add this setting)&lt;br /&gt;
&lt;br /&gt;
For example&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!--&lt;br /&gt;
    //Coded path to be used when external only ip address might be used blocking titan from talking to asp bridge&lt;br /&gt;
    //also requires CRM setting IPAddressChecking to be disabled&lt;br /&gt;
    --&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMCodedPath&amp;quot; value=&amp;quot;http://localhost/crm/&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This can happen to any application written in Titan so this applies to all products.&lt;br /&gt;
&lt;br /&gt;
2. NT Authenication Error&lt;br /&gt;
&lt;br /&gt;
Depending on the IIS setup you may need to add in a windows users details to the web.config file. This usually occurs when IIS requires authentication.&lt;br /&gt;
&lt;br /&gt;
Set the following values to be a relevenat user. It is best to ensure that the users password does not expire.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkUser&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkUserPassword&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;add key=&amp;quot;CRMNetworkDomain&amp;quot; value=&amp;quot;&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
(Note: you may need to add these settings)&lt;br /&gt;
&lt;br /&gt;
3. Fiddler is a great tool for debugging HTTP requests.&lt;br /&gt;
&lt;br /&gt;
One thing to remember is..&lt;br /&gt;
&lt;br /&gt;
Important: Regardless of other settings, .NET will always bypass the Fiddler proxy for URLs containing localhost.  So, rather than using localhost, change your code to refer to the machine name.  For instance:&lt;br /&gt;
&lt;br /&gt;
    Does not show in Fiddler: http://localhost/X509SignCodeService/X509SigningService.asmx&lt;br /&gt;
&lt;br /&gt;
    Shows in Fiddler: http://mymachine/X509SignCodeService/X509SigningService.asmx&lt;br /&gt;
&lt;br /&gt;
4. Parameter name cannot be zero&lt;br /&gt;
&lt;br /&gt;
This is an error on the Accelerator license. Something has changed or broken the license.&lt;br /&gt;
Should be fixed in an upcoming release (after Jan 2012)&lt;br /&gt;
&lt;br /&gt;
5. 500.21 (pagehandlerfactory integrated has a Bad Module)&lt;br /&gt;
&lt;br /&gt;
http://blogs.microsoft.co.il/blogs/gadib/archive/2010/10/26/iis-error-handler-pagehandlerfactory-integrated-has-a-bad-module-managedpipelinehandler-in-its-moudle-list.aspx&lt;br /&gt;
&lt;br /&gt;
it seems .net 4.0 might not be installed .&lt;br /&gt;
&lt;br /&gt;
see also&lt;br /&gt;
&lt;br /&gt;
http://www.compdigitec.com/labs/2010/07/12/solving-handler-pagehandlerfactory-integrated-has-a-bad-module-managedpipelinehandler-in-asp-net-4-0/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Class not registered, ClassID: {7C6E29BC-8B8B-4C3D-859E-AF6CD158BE0F} &lt;br /&gt;
&lt;br /&gt;
The issue here is that the &lt;br /&gt;
&lt;br /&gt;
   MSXML 4.0 parser&lt;br /&gt;
&lt;br /&gt;
component is missing and this is used by SOAP to connect to the CRM web services&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=277</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=277"/>
		<updated>2016-08-29T09:15:27Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to backup your CRM and CRMSelfService DB&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRM] TO  DISK = N&#039;C:\DB Backups\CRM.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRM-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
BACKUP DATABASE [CRMSelfService] TO  DISK = N&#039;C:\DB Backups\CRMSelfService.bak&#039; WITH FORMAT, INIT,  NAME = N&#039;CRMSelfService-Full Database Backup&#039;, SKIP, NOREWIND, NOUNLOAD,  STATS = 10&lt;br /&gt;
GO&lt;br /&gt;
&lt;br /&gt;
* C:\DB Backups\ is a folder on the server&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=276</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=276"/>
		<updated>2016-08-29T09:02:17Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Some queries to estimate the size of a database&lt;br /&gt;
&lt;br /&gt;
SELECT &lt;br /&gt;
      database_name = DB_NAME(database_id)&lt;br /&gt;
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;LOG&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = &#039;ROWS&#039; THEN size END) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))&lt;br /&gt;
FROM sys.master_files WITH(NOWAIT)&lt;br /&gt;
WHERE database_id = DB_ID() -- for current db &lt;br /&gt;
GROUP BY database_id&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/18014392/select-sql-server-database-size&lt;br /&gt;
&lt;br /&gt;
with fs&lt;br /&gt;
as&lt;br /&gt;
(&lt;br /&gt;
    select database_id, type, size * 8.0 / 1024 size&lt;br /&gt;
    from sys.master_files&lt;br /&gt;
)&lt;br /&gt;
select &lt;br /&gt;
    name,&lt;br /&gt;
    (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,&lt;br /&gt;
    (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB&lt;br /&gt;
from sys.databases db&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/5945360/sql-server-2008-how-to-query-all-databases-sizes&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Troubleshooting&amp;diff=275</id>
		<title>Troubleshooting</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Troubleshooting&amp;diff=275"/>
		<updated>2016-07-19T12:50:05Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;1. CRM Indexor service not indexing&lt;br /&gt;
 &lt;br /&gt;
This uses a folder in the library called&lt;br /&gt;
&lt;br /&gt;
...Sage\CRM\CRM71a\Library\FullText.ix&lt;br /&gt;
&lt;br /&gt;
If you delete this folder and restart the “CRM Indexer service” this should repopulate and correct the issue&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/5514/13711.aspx#13711&lt;br /&gt;
&lt;br /&gt;
2. Moving CRM (web services not working - &#039;Class not registered, ClassID&#039;)&lt;br /&gt;
&lt;br /&gt;
Open command prompt on CRMDotNet folder&lt;br /&gt;
&lt;br /&gt;
Example Folder: C:\Program Files (x86)\Sage\CRM\CRMDotNet\6.2&lt;br /&gt;
&lt;br /&gt;
  Unregister:&lt;br /&gt;
&lt;br /&gt;
    gacutil /uf SageCRMNet&lt;br /&gt;
&lt;br /&gt;
    regasm /unregister SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
    gacutil /uf SageCrmWrapper&lt;br /&gt;
&lt;br /&gt;
    regasm /unregister SageCrmWrapper.dll&lt;br /&gt;
&lt;br /&gt;
  Register:&lt;br /&gt;
&lt;br /&gt;
    gacutil /if SageCrmWrapper.dll&lt;br /&gt;
&lt;br /&gt;
    gacutil /if SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
    regasm SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
Also make sure to install MSXML parser 4.0 (later versions will not suffice) - this comes with a CRM install&lt;br /&gt;
&lt;br /&gt;
3. &amp;quot;Error, you need to be an administrator on the CRM server to use this function.&amp;quot;&lt;br /&gt;
So in IIS, expand the server name in the list where web deployment or CRM is running, then expand Web Sites, then Default Web Site.&lt;br /&gt;
&lt;br /&gt;
Right-click the name of the CRM instance and click Properties.&lt;br /&gt;
&lt;br /&gt;
Click the Directory Security tab, then Edit in the Anonymous access and authentication control.&lt;br /&gt;
&lt;br /&gt;
In the Authentication Methods window, check the &amp;quot;Integrated Windows authentication&amp;quot; option. Select Anonymous Authentication, click edit, set the credentials to use &amp;quot;Application pool identity&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Click OK to exit the windows.&lt;br /&gt;
&lt;br /&gt;
An IIS reset will be warranted after making this change.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/3439/7576.aspx#7576&lt;br /&gt;
&lt;br /&gt;
*If you get a windows challenge you need to disable the &amp;quot;Windows Authentication&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
4. SQL Express default password for Sage CRM&lt;br /&gt;
&lt;br /&gt;
In SQL Express the default password is &lt;br /&gt;
&lt;br /&gt;
SageCRMv71&lt;br /&gt;
&lt;br /&gt;
5. Registry&lt;br /&gt;
&lt;br /&gt;
The sage crm core settings are stored in the windows registry&lt;br /&gt;
&lt;br /&gt;
Sample path&lt;br /&gt;
&lt;br /&gt;
  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\eWare\Config\/CRM&lt;br /&gt;
&lt;br /&gt;
you can change the core crm db here if needed&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Currency not set&lt;br /&gt;
&lt;br /&gt;
This can be caused by data in the system having a wrong/invalid currency. We have seen lists not display due to this even though the data that they select has valid data.&lt;br /&gt;
The fix for this is to update the data _CID values so that they have a valid currency (used in the system)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;This Quote/Order is read only because of changes made in the OE Admin&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This error occurs, when the Pricelist field is not shown on the the Quotessummary screen.&lt;br /&gt;
&lt;br /&gt;
I have a workaround, the default value of this list is &amp;quot;default&amp;quot; and the field security is readonly, so no one can change this settings. this will only be practicalbe when only the default pricelist is configured.&lt;br /&gt;
&lt;br /&gt;
Ref:https://community.sagecrm.com/user_community/f/84/t/3589.aspx&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Troubleshooting&amp;diff=274</id>
		<title>Troubleshooting</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Troubleshooting&amp;diff=274"/>
		<updated>2016-07-19T12:49:50Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;1. CRM Indexor service not indexing&lt;br /&gt;
 &lt;br /&gt;
This uses a folder in the library called&lt;br /&gt;
&lt;br /&gt;
...Sage\CRM\CRM71a\Library\FullText.ix&lt;br /&gt;
&lt;br /&gt;
If you delete this folder and restart the “CRM Indexer service” this should repopulate and correct the issue&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/5514/13711.aspx#13711&lt;br /&gt;
&lt;br /&gt;
2. Moving CRM (web services not working - &#039;Class not registered, ClassID&#039;)&lt;br /&gt;
&lt;br /&gt;
Open command prompt on CRMDotNet folder&lt;br /&gt;
&lt;br /&gt;
Example Folder: C:\Program Files (x86)\Sage\CRM\CRMDotNet\6.2&lt;br /&gt;
&lt;br /&gt;
  Unregister:&lt;br /&gt;
&lt;br /&gt;
    gacutil /uf SageCRMNet&lt;br /&gt;
&lt;br /&gt;
    regasm /unregister SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
    gacutil /uf SageCrmWrapper&lt;br /&gt;
&lt;br /&gt;
    regasm /unregister SageCrmWrapper.dll&lt;br /&gt;
&lt;br /&gt;
  Register:&lt;br /&gt;
&lt;br /&gt;
    gacutil /if SageCrmWrapper.dll&lt;br /&gt;
&lt;br /&gt;
    gacutil /if SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
    regasm SageCRMNet.dll&lt;br /&gt;
&lt;br /&gt;
Also make sure to install MSXML parser 4.0 (later versions will not suffice) - this comes with a CRM install&lt;br /&gt;
&lt;br /&gt;
3. &amp;quot;Error, you need to be an administrator on the CRM server to use this function.&amp;quot;&lt;br /&gt;
So in IIS, expand the server name in the list where web deployment or CRM is running, then expand Web Sites, then Default Web Site.&lt;br /&gt;
&lt;br /&gt;
Right-click the name of the CRM instance and click Properties.&lt;br /&gt;
&lt;br /&gt;
Click the Directory Security tab, then Edit in the Anonymous access and authentication control.&lt;br /&gt;
&lt;br /&gt;
In the Authentication Methods window, check the &amp;quot;Integrated Windows authentication&amp;quot; option. Select Anonymous Authentication, click edit, set the credentials to use &amp;quot;Application pool identity&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Click OK to exit the windows.&lt;br /&gt;
&lt;br /&gt;
An IIS reset will be warranted after making this change.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/3439/7576.aspx#7576&lt;br /&gt;
&lt;br /&gt;
*If you get a windows challenge you need to disable the &amp;quot;Windows Authentication&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
4. SQL Express default password for Sage CRM&lt;br /&gt;
&lt;br /&gt;
In SQL Express the default password is &lt;br /&gt;
&lt;br /&gt;
SageCRMv71&lt;br /&gt;
&lt;br /&gt;
5. Registry&lt;br /&gt;
&lt;br /&gt;
The sage crm core settings are stored in the windows registry&lt;br /&gt;
&lt;br /&gt;
Sample path&lt;br /&gt;
&lt;br /&gt;
  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\eWare\Config\/CRM&lt;br /&gt;
&lt;br /&gt;
you can change the core crm db here if needed&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Currency not set&lt;br /&gt;
&lt;br /&gt;
This can be caused by data in the system having a wrong/invalid currency. We have seen lists not display due to this even though the data that they select has valid data.&lt;br /&gt;
The fix for this is to update the data _CID values so that they have a valid currency (used in the system)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
This Quote/Order is read only because of changes made in the OE Admin&lt;br /&gt;
&lt;br /&gt;
This error occurs, when the Pricelist field is not shown on the the Quotessummary screen.&lt;br /&gt;
&lt;br /&gt;
I have a workaround, the default value of this list is &amp;quot;default&amp;quot; and the field security is readonly, so no one can change this settings. this will only be practicalbe when only the default pricelist is configured.&lt;br /&gt;
&lt;br /&gt;
Ref:https://community.sagecrm.com/user_community/f/84/t/3589.aspx&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Table_Scripting&amp;diff=273</id>
		<title>Table Scripting</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Table_Scripting&amp;diff=273"/>
		<updated>2016-07-18T19:21:54Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
This sample shows you how to check if the field has been changed from one value to another&lt;br /&gt;
&lt;br /&gt;
  function UpdateRecord()&lt;br /&gt;
  {&lt;br /&gt;
    if (Values(&amp;quot;case_AssignedUserId&amp;quot;)+&amp;quot;&amp;quot;==&amp;quot;undefined&amp;quot;)&lt;br /&gt;
      return;  //bad update from crm..or field not changed&lt;br /&gt;
    var CaseRec=CRM.CreateQueryObj(&amp;quot;SELECT * FROM Cases WITH (NOLOCK) WHERE &amp;quot; + WhereClause);&lt;br /&gt;
    CaseRec.SelectSQL();&lt;br /&gt;
    if (CaseRec(&amp;quot;case_assigneduserid&amp;quot;)!=Values(&amp;quot;Case_AssignedUserId&amp;quot;))&lt;br /&gt;
    {&lt;br /&gt;
      ErrorStr=&amp;quot;field value has changed from &amp;quot;+CaseRec(&amp;quot;case_assigneduserid&amp;quot;) +&amp;quot; to &amp;quot;+Values(&amp;quot;Case_AssignedUserId&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Altering CRM dates in Table level scripts&lt;br /&gt;
&lt;br /&gt;
  var mydate = new Date();&lt;br /&gt;
  mydate.setDate(mydate.getDate() +7);&lt;br /&gt;
  Values(&amp;quot;comp_customerstartdate&amp;quot;) = mydate.getVarDate();&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2011/03/07/setting-or-updating-date-fields-using-a-table-level-script.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Comparing previous values (in cases where you might want to run some code only when a field value has changed)&lt;br /&gt;
&lt;br /&gt;
Within the UpdateRecord method stub you would first query the current record using&lt;br /&gt;
&lt;br /&gt;
  var crec=CRM.FindRecord(&amp;quot;agreement&amp;quot;,WhereClause);&lt;br /&gt;
&lt;br /&gt;
You would then compare values as in&lt;br /&gt;
&lt;br /&gt;
  if (crec(&amp;quot;comp_name&amp;quot;)!=Values(&amp;quot;comp_name&amp;quot;))...&lt;br /&gt;
&lt;br /&gt;
For date fields you have to create a Date object&lt;br /&gt;
&lt;br /&gt;
  var c_comp_renewaldate = new Date(crec(&amp;quot;comp_renewaldate&amp;quot;));&lt;br /&gt;
  var v_comp_renewaldate = new Date(Values(&amp;quot;comp_renewaldate&amp;quot;));&lt;br /&gt;
&lt;br /&gt;
and then call the getDate() method of the Date object to do the comparison.&lt;br /&gt;
You cannot compare the date objects as it will never match&lt;br /&gt;
&lt;br /&gt;
  if (c_comp_renewaldate.getDate() != v_comp_renewaldate.getDate())...&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful learning tool if your trying to work out when each of the TLS functions are called.  &lt;br /&gt;
&lt;br /&gt;
Table level script will log all events to the SQL logs&lt;br /&gt;
&lt;br /&gt;
  function log(message, error) {try{CRM.CreateQueryObj(&#039;/* &#039;+((error)?message:message+&#039; */&#039;)).SelectSql();}catch(e){}}&lt;br /&gt;
  function InsertRecord() { log(&amp;quot;InsertRecord called&amp;quot;,1); }&lt;br /&gt;
  function PostInsertRecord() { log(&amp;quot;PostInsertRecord called&amp;quot;,1); }&lt;br /&gt;
  function UpdateRecord() { log(&amp;quot;UpdateRecord called.  WHERECLAUSE=&amp;quot; + WHERECLAUSE,1); }&lt;br /&gt;
  function DeleteRecord() { log(&amp;quot;DeleteRecord called.  WHERECLAUSE=&amp;quot; + WHERECLAUSE,1); }&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2011/08/19/how-do-you-know-if-your-table-level-scripts-are-being-executed.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Function to get the SID from within a table level script - you may want to do this to call an asp page via ajax for example&lt;br /&gt;
&lt;br /&gt;
Based off of code at: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2008/03/25/how-can-i-get-the-sid-in-serverside-scripting.aspx&lt;br /&gt;
&lt;br /&gt;
  function getsid()&lt;br /&gt;
  {&lt;br /&gt;
    var strPath = new String(CRM.URL(200));&lt;br /&gt;
    var arrayFullKeys = strPath.split(&amp;quot;?&amp;quot;);&lt;br /&gt;
    var arrayKeys = arrayFullKeys[1].split(&amp;quot;&amp;amp;&amp;quot;);&lt;br /&gt;
    for (var i=0;i&amp;lt;arrayKeys.length;i++)&lt;br /&gt;
    {&lt;br /&gt;
       var arrayValue = arrayKeys[i].split(&amp;quot;=&amp;quot;);&lt;br /&gt;
       if (arrayValue[0].toLowerCase()== &amp;quot;sid&amp;quot;)&lt;br /&gt;
       {&lt;br /&gt;
            return arrayValue[1];&lt;br /&gt;
       }&lt;br /&gt;
   }&lt;br /&gt;
   return &amp;quot;&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To Make an Ajax GET request call from within a table script&lt;br /&gt;
&lt;br /&gt;
  function MakeAjaxPostRequest(RequestPath)&lt;br /&gt;
  {&lt;br /&gt;
    var XmlHttp = new ActiveXObject(&amp;quot;Microsoft.XMLHTTP&amp;quot;);&lt;br /&gt;
    XmlHttp.open(&#039;GET&#039;,RequestPath,false);&lt;br /&gt;
    XmlHttp.send();&lt;br /&gt;
    XmlHttp=null; // always clear the XmlHttp object when you are done to avoid memory leaks&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
PostInsertRecord&lt;br /&gt;
&lt;br /&gt;
https://community.sagecrm.com/user_community/f/84/t/10447.aspx&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Errorsettings.png&amp;diff=272</id>
		<title>File:Errorsettings.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Errorsettings.png&amp;diff=272"/>
		<updated>2016-05-18T09:40:12Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Errorpage2.png&amp;diff=271</id>
		<title>File:Errorpage2.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Errorpage2.png&amp;diff=271"/>
		<updated>2016-05-18T09:39:53Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Config&amp;diff=270</id>
		<title>Config</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Config&amp;diff=270"/>
		<updated>2016-05-18T09:39:40Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Turn on debugging in IE and IIS (for when you see 500 errors - these are useless)&lt;br /&gt;
&lt;br /&gt;
IE settings (uncheck “Show friendly HTTP error messages)&lt;br /&gt;
&lt;br /&gt;
[[File:findclick.png]]&lt;br /&gt;
&lt;br /&gt;
Open IIS and select the CRM instance&lt;br /&gt;
&lt;br /&gt;
[[File:asp.png]]&lt;br /&gt;
 &lt;br /&gt;
Click ASP&lt;br /&gt;
&lt;br /&gt;
[[File:senderror.png]]&lt;br /&gt;
 &lt;br /&gt;
Change the “Send Errors to Browser” to be True&lt;br /&gt;
Select the CRM name again&lt;br /&gt;
 &lt;br /&gt;
[[File:errorpage1.png]]&lt;br /&gt;
&lt;br /&gt;
Double Click Error Pages&lt;br /&gt;
 &lt;br /&gt;
[[File:errorpage2.png]]&lt;br /&gt;
&lt;br /&gt;
Click “Edit Feature Settings…”&lt;br /&gt;
 &lt;br /&gt;
[[File:errorsettings.png]]&lt;br /&gt;
&lt;br /&gt;
Select the “Detailed errors”&lt;br /&gt;
Click OK&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
You see this error when you try change pages in the admin area.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Error, you need to be an administrator on the CRM server to use this function.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In IIS, expand the server name in the list where web deployment or CRM is running, then expand Web Sites, then Default Web Site.&lt;br /&gt;
&lt;br /&gt;
Right-click the name of the CRM instance and click Properties.&lt;br /&gt;
&lt;br /&gt;
Click the Directory Security tab, then Edit in the Anonymous access and authentication control.&lt;br /&gt;
&lt;br /&gt;
In the Authentication Methods window, check the &amp;quot;Integrated Windows authentication&amp;quot; option.&lt;br /&gt;
&lt;br /&gt;
Click OK to exit the windows.&lt;br /&gt;
&lt;br /&gt;
An IIS reset will be warranted after making this change.&lt;br /&gt;
&lt;br /&gt;
*If the option is missing see how to enable it at this link&lt;br /&gt;
&lt;br /&gt;
http://weblogs.asp.net/zroiy/archive/2008/08/17/missing-windows-authentication-provider-for-iis-7-on-windows-server-2008.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
HTTP Error 404.11 - Not Found The request filtering module is configured to deny a request that contains a double escape sequence.&lt;br /&gt;
&lt;br /&gt;
Encountered on some environments&lt;br /&gt;
&lt;br /&gt;
Ref: http://www.britishdeveloper.co.uk/2013/02/the-request-filtering-module-is.html&lt;br /&gt;
&lt;br /&gt;
The quick fix&lt;br /&gt;
&lt;br /&gt;
This can be easily achieved with a simple web.config change (located in &amp;quot;\WWWRoot\web.config&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
  &amp;lt;system.webServer&amp;gt;&lt;br /&gt;
    &amp;lt;security&amp;gt;&lt;br /&gt;
        &amp;lt;requestFiltering allowDoubleEscaping=&amp;quot;true&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;/security&amp;gt;&lt;br /&gt;
  &amp;lt;/system.webServer&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Errorpage1.png&amp;diff=269</id>
		<title>File:Errorpage1.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Errorpage1.png&amp;diff=269"/>
		<updated>2016-05-18T09:38:59Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Senderror.png&amp;diff=268</id>
		<title>File:Senderror.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Senderror.png&amp;diff=268"/>
		<updated>2016-05-18T09:38:40Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Asp.png&amp;diff=267</id>
		<title>File:Asp.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Asp.png&amp;diff=267"/>
		<updated>2016-05-18T09:38:23Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=File:Findclick.png&amp;diff=266</id>
		<title>File:Findclick.png</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=File:Findclick.png&amp;diff=266"/>
		<updated>2016-05-18T09:37:56Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Config&amp;diff=265</id>
		<title>Config</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Config&amp;diff=265"/>
		<updated>2016-05-18T09:37:33Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Turn on debugging in IE and IIS (for when you see 500 errors - these are useless)&lt;br /&gt;
&lt;br /&gt;
IE settings (uncheck “Show friendly HTTP error messages)&lt;br /&gt;
&lt;br /&gt;
[[File:findclick.png]]&lt;br /&gt;
&lt;br /&gt;
Open IIS and select the CRM instance&lt;br /&gt;
&lt;br /&gt;
[[File:asp.png]]&lt;br /&gt;
 &lt;br /&gt;
Click ASP&lt;br /&gt;
&lt;br /&gt;
[[File:senderror.png]]&lt;br /&gt;
 &lt;br /&gt;
Change the “Send Errors to Browser” to be True&lt;br /&gt;
Select the CRM name again&lt;br /&gt;
 &lt;br /&gt;
[[File:errorpage1.png]]&lt;br /&gt;
&lt;br /&gt;
Double Click Error Pages&lt;br /&gt;
 &lt;br /&gt;
Click “Edit Feature Settings…”&lt;br /&gt;
 &lt;br /&gt;
[[File:errorsettings.png]]&lt;br /&gt;
&lt;br /&gt;
Select the “Detailed errors”&lt;br /&gt;
Click OK&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
You see this error when you try change pages in the admin area.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Error, you need to be an administrator on the CRM server to use this function.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In IIS, expand the server name in the list where web deployment or CRM is running, then expand Web Sites, then Default Web Site.&lt;br /&gt;
&lt;br /&gt;
Right-click the name of the CRM instance and click Properties.&lt;br /&gt;
&lt;br /&gt;
Click the Directory Security tab, then Edit in the Anonymous access and authentication control.&lt;br /&gt;
&lt;br /&gt;
In the Authentication Methods window, check the &amp;quot;Integrated Windows authentication&amp;quot; option.&lt;br /&gt;
&lt;br /&gt;
Click OK to exit the windows.&lt;br /&gt;
&lt;br /&gt;
An IIS reset will be warranted after making this change.&lt;br /&gt;
&lt;br /&gt;
*If the option is missing see how to enable it at this link&lt;br /&gt;
&lt;br /&gt;
http://weblogs.asp.net/zroiy/archive/2008/08/17/missing-windows-authentication-provider-for-iis-7-on-windows-server-2008.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
HTTP Error 404.11 - Not Found The request filtering module is configured to deny a request that contains a double escape sequence.&lt;br /&gt;
&lt;br /&gt;
Encountered on some environments&lt;br /&gt;
&lt;br /&gt;
Ref: http://www.britishdeveloper.co.uk/2013/02/the-request-filtering-module-is.html&lt;br /&gt;
&lt;br /&gt;
The quick fix&lt;br /&gt;
&lt;br /&gt;
This can be easily achieved with a simple web.config change (located in &amp;quot;\WWWRoot\web.config&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
  &amp;lt;system.webServer&amp;gt;&lt;br /&gt;
    &amp;lt;security&amp;gt;&lt;br /&gt;
        &amp;lt;requestFiltering allowDoubleEscaping=&amp;quot;true&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;/security&amp;gt;&lt;br /&gt;
  &amp;lt;/system.webServer&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=264</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=264"/>
		<updated>2016-04-13T16:16:10Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;br /&gt;
&lt;br /&gt;
SELECT @@VERSION&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=263</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=263"/>
		<updated>2016-04-13T12:08:35Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to check the database settings&lt;br /&gt;
&lt;br /&gt;
  dbcc useroptions&lt;br /&gt;
  go&lt;br /&gt;
  sp_configure &#039;default language&#039;&lt;br /&gt;
  go&lt;br /&gt;
  sp_helplanguage&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: sp_configure &#039;default language&#039; will return a code and you use sp_helplanguage to check out the value&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Tomcat&amp;diff=262</id>
		<title>Tomcat</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Tomcat&amp;diff=262"/>
		<updated>2016-03-29T09:49:14Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Tomcat fails to start, commons-daemon.2015-12-10.log shows:&lt;br /&gt;
&lt;br /&gt;
[2015-12-11 08:18:45] [error] CreateJavaVM Failed&lt;br /&gt;
&lt;br /&gt;
[2015-12-11 08:18:45] [error] Failed to start Java&lt;br /&gt;
&lt;br /&gt;
[2015-12-11 08:18:45] [error] ServiceStart returned 4&lt;br /&gt;
&lt;br /&gt;
The registry setting is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Apache Software Foundation\Procrun 2.0\CRMTomcat7\Parameters\Java and you need to change the JvmMx and JvmSs by half so they look like this.&lt;br /&gt;
&lt;br /&gt;
JvmMx    0x00000200 (512)&lt;br /&gt;
&lt;br /&gt;
JvmSs    0x00000400 (1024)&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/t/12540.aspx&lt;br /&gt;
&lt;br /&gt;
*confirmed as a working fix &lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Easiest option here is to re-install (actually select the upgrade option) a patch and this usually works. &lt;br /&gt;
&lt;br /&gt;
Latest guide (7.3)&lt;br /&gt;
&lt;br /&gt;
https://community.sagecrm.com/knowledgebase/w/onpremisekba/1074.632-17360-sage-crm-interactive-dashboard-support-guide.aspx#CommonErrors&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
*below no longer applies to newer versions of CRM&lt;br /&gt;
&lt;br /&gt;
Java versions later than&lt;br /&gt;
&lt;br /&gt;
version 6 update 27&lt;br /&gt;
&lt;br /&gt;
will cause issues (tomcat wont work and the report export might error out with &amp;quot;win 32 code 1 incorrect function&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
use this too test the version of java on the machine&lt;br /&gt;
&lt;br /&gt;
http://www.javatester.org/version.html&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Troubleshooting:&lt;br /&gt;
&lt;br /&gt;
1. Ensure parent paths is set to true for ASP&lt;br /&gt;
&lt;br /&gt;
..details are being investigated still&lt;br /&gt;
&lt;br /&gt;
ISAPI Rewriting&lt;br /&gt;
&lt;br /&gt;
*IIS 6 only seems to need the file mentioned in 1 below&lt;br /&gt;
1. Sage use a file called &amp;quot;....Sage\CRM\Services\IISUtils\CRMRewriter\ISAPI_Rewrite.dll&amp;quot; which is created by &amp;quot;Helicon&amp;quot; (http://www.isapirewrite.com/)&lt;br /&gt;
&lt;br /&gt;
2. The rewriting rules are written in &amp;quot;....Sage\CRM\Services\IISUtils\CRMRewriter\CRM.Rewriter.rules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
3. Re-writing essentially maps urls such as &amp;quot;http://localhost/sdata/crm71sp2j/layout/-/$service/&amp;quot; to &amp;quot;http://localhost:10009/crm71j/..etc&amp;quot;. So you can see that the port is 10009 and this is the port that TOMCAT is working through.&lt;br /&gt;
&lt;br /&gt;
404&#039;s usually appear when the &amp;quot;RewriterModule&amp;quot; is missing from IIS&lt;br /&gt;
&lt;br /&gt;
This should be added to IIS. To do this select the application (or main node) and select &amp;quot;Modules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
From there click &amp;quot;Add Managed Modules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Set the name to be &amp;quot;RewriterModule&amp;quot;&lt;br /&gt;
&lt;br /&gt;
and the type to be &amp;quot;ManagedFusion.Rewriter.RewriterModule, ManagedFusion.Rewriter&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Note that this should map the setting in the web.config file&lt;br /&gt;
&lt;br /&gt;
		&amp;lt;httpModules&amp;gt;&lt;br /&gt;
			&amp;lt;add name=&amp;quot;RewriterModule&amp;quot; type=&amp;quot;ManagedFusion.Rewriter.RewriterModule, ManagedFusion.Rewriter&amp;quot; /&amp;gt;&lt;br /&gt;
		&amp;lt;/httpModules&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do not check the &amp;quot;Invoke only for requests to ASP.Net applications or Managed handlers&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Useful articles:&lt;br /&gt;
&lt;br /&gt;
http://aspnet.4guysfromrolla.com/articles/011404-1.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Dashboard not working outside of intranet&lt;br /&gt;
&lt;br /&gt;
The rewriter&#039;s probably trying to send the request to Tomcat to the external IP. &lt;br /&gt;
&lt;br /&gt;
In v7.1, It will look something like this, for a static IP of 50.57.215.216:&lt;br /&gt;
&lt;br /&gt;
Initial request:&lt;br /&gt;
&lt;br /&gt;
  http:// 50.57.215.216/sdata/crmj/layout/-/$service/lockrecord?tableName=LPLayout&amp;amp;id=6010&amp;amp;SID=47373617139422&amp;amp;contextEntityId=-1&amp;amp;contextRecordId=-1&lt;br /&gt;
&lt;br /&gt;
This is rewritten to:&lt;br /&gt;
&lt;br /&gt;
  http:// 50.57.215.216:10009/crmj/layout/-/$service/lockrecord?tableName=LPLayout&amp;amp;id=6010&amp;amp;SID=47373617139422&amp;amp;contextEntityId=-1&amp;amp;contextRecordId=-1&lt;br /&gt;
&lt;br /&gt;
The Tomcat port is unlikely to be accessible using the static IP. &lt;br /&gt;
The usual way I&#039;d suggest working around this is to use a fully-qualified name, and add an entry to the server&#039;s hosts file so that the FQDN will resolve to 127.0.0.1. &lt;br /&gt;
I would not suggest opening the Tomcat port for requests using the static IP.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/t/9983.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Seen on 7.2&lt;br /&gt;
&lt;br /&gt;
If you move installs you can get issues with the mail merge (dashboard might still work) if you dont have the same &#039;javapath&#039; set in custom_sysparams&lt;br /&gt;
&lt;br /&gt;
Sample code to fix this&lt;br /&gt;
&lt;br /&gt;
  update custom_sysparams&lt;br /&gt;
    set parm_value=&#039;C:\Program Files (x86)\Sage\CRM\Services\JRE\jre7\bin\&#039;&lt;br /&gt;
       where parm_name=&#039;javapath&#039;&lt;br /&gt;
&lt;br /&gt;
The error might be reported as &lt;br /&gt;
&lt;br /&gt;
  com.sage.crm.web.exception.SageAsyncProcessException: Mailmerge generation failed&lt;br /&gt;
  Caused by: com.sage.crm.core.exception.SageEndpointException: java.io.IOException: Cannot run program&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
7.2b seems to need port 11009 (used to be 10009) to be open for external ips to get access to the dashboard&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=External_Links&amp;diff=261</id>
		<title>External Links</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=External_Links&amp;diff=261"/>
		<updated>2016-03-22T14:37:47Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Developer Help&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[http://sagecity.na.sage.com/support_communities/sage_crm/default.aspx &#039;NA Sage city forum&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://help.sagecrm.com/on_premise/en/7.3SP1/dev/#Developer/ASP%20Object%20Reference/CRMQuery%20Object/AS_CRMQExecSql.htm#kanchor449 &#039;Sage CRM Developer Help&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://help.sagecrm.com/on_premise/en/7.3SP1/admin/ &#039;Sage CRM Admin Help&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://help.sagecrm.com/js-api/classes/caption.html &#039;Client Side API&#039;]&lt;br /&gt;
&lt;br /&gt;
[https://community.sagecrm.com/ &#039;Sage CRM Community&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://community.sagesoftware.com/ &#039;NA Sage Community Forums&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://community.sagesoftware.com/t5/Sage-Pro-ERP-Forum/bd-p/SageProERPForum &#039;Sage Pro ERP Forum&#039;]&lt;br /&gt;
&lt;br /&gt;
Useful tools&lt;br /&gt;
&lt;br /&gt;
[http://regexpal.com/ &#039;Test Regex expressions&#039;]&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Configuration&amp;diff=260</id>
		<title>Configuration</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Configuration&amp;diff=260"/>
		<updated>2016-02-17T10:42:03Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Error - IP Address Mismatch &lt;br /&gt;
&lt;br /&gt;
Log on to the server and open regedit and the CRM settings&lt;br /&gt;
&lt;br /&gt;
Change the key value &amp;quot;IPAddressChecking&amp;quot; to be N&lt;br /&gt;
&lt;br /&gt;
IIS needs to be reset for the change to take effect&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you install SQL Express the system will setup a default sa password as&lt;br /&gt;
&lt;br /&gt;
  SageCRMv71&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/6017/22204.aspx#22204&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To expose emailtemplates to CRM run the following update in SQL&lt;br /&gt;
&lt;br /&gt;
  update Custom_Tables&lt;br /&gt;
    set Bord_Hidden=null&lt;br /&gt;
    where Bord_Name=&#039;EmailTemplates&#039;&lt;br /&gt;
&lt;br /&gt;
and then reload metadata (or restart IIS)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
HTTP 403.14 Forbidden Error &lt;br /&gt;
&lt;br /&gt;
This can happen in CRM with development of custom pages especially when changing from admin mode to Normal user mode&lt;br /&gt;
&lt;br /&gt;
A work around to top this happening is to create a default page in the &amp;quot;CRM/custompages&amp;quot; folder&lt;br /&gt;
&lt;br /&gt;
This page redirects the user to some location (our example goes to action 183. &lt;br /&gt;
&lt;br /&gt;
  var newUrl=CRM.Url(183);&lt;br /&gt;
  Response.Redirect(newUrl);&lt;br /&gt;
&lt;br /&gt;
Within IIS you have to add your file name as a default document at the custompages folder level&lt;br /&gt;
&lt;br /&gt;
[[File:403index.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Ref: https://support.na.sage.com/selfservice/viewContent.do?externalId=39716&amp;amp;sliceId=1&lt;br /&gt;
&lt;br /&gt;
Description&lt;br /&gt;
	&lt;br /&gt;
How to configure CRM 7.2 for IIS Auto Login&lt;br /&gt;
Resolution&lt;br /&gt;
	&lt;br /&gt;
&lt;br /&gt;
    Open the IIS Manager&lt;br /&gt;
    Click on the CRM site&lt;br /&gt;
    Click Basic Settings&lt;br /&gt;
    Set the Connect As setting to &#039;Application User (Pass-through Authentication)&#039;&lt;br /&gt;
    Click on the CRM site&lt;br /&gt;
    Open the Authentication inteface&lt;br /&gt;
    Enable Anonymous and Windows Authentication (**** in fact this is wrong according to https://community.sagecrm.com/knowledgebase/w/onpremisekba/760.536-17048-http-401-5-using-iis-autologin.aspx  -see below)&lt;br /&gt;
    Select Anonymous Authentication and click Edit&lt;br /&gt;
    Set the Anonymous Authentication to use the Application Pool Identity&lt;br /&gt;
    Open Internet Explorer and log in to CRM&lt;br /&gt;
    Setup all your user accounts so that the usernames matches the usernames Active Directory&lt;br /&gt;
    Click Administration, Users, User Configuration&lt;br /&gt;
    Click Change&lt;br /&gt;
    Set IIS Auto Login to Yes&lt;br /&gt;
    Set the Default Domain for IIS Auto Login to match your Windows Domain&lt;br /&gt;
    Open SQL Management Studio&lt;br /&gt;
    Click New Query&lt;br /&gt;
    use [CRM Databasename]&lt;br /&gt;
    go&lt;br /&gt;
    update users set user_password = NULL&lt;br /&gt;
    Do an IISReset&lt;br /&gt;
    Open Internet Explorer&lt;br /&gt;
    Go to Internet Options&lt;br /&gt;
    Add the CRM site to Trusted Sites&lt;br /&gt;
    Click the Custom Level option under Security&lt;br /&gt;
    Under User Authentication, set the option to &#039;Automatic Logon with Current Username and Password&#039;&lt;br /&gt;
    Repeat step 19-23 on all workstations&lt;br /&gt;
&lt;br /&gt;
ref: https://community.sagecrm.com/knowledgebase/w/onpremisekba/760.536-17048-http-401-5-using-iis-autologin.aspx&lt;br /&gt;
&lt;br /&gt;
Summary:&lt;br /&gt;
&lt;br /&gt;
A login prompt may appear when logging into CRM using IIS autologin. On entering a username and password, a 401.5 (Unauthorized) error page may appear.&lt;br /&gt;
&lt;br /&gt;
Resolution:&lt;br /&gt;
&lt;br /&gt;
This issue may be caused by having Anonymous authentication enabled on the CRM virtual directory in IIS. When using IIS autologin, only Windows authentication should be enabled.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
The following may assist in troubleshooting IIS autologin cases:&lt;br /&gt;
&lt;br /&gt;
    On the client machine, open a command prompt and run the &amp;quot;whoami&amp;quot; command. This will return the domain\username you should be using in CRM. The domain goes in the Default Domain for IIS login field in Administration -&amp;gt; Users -&amp;gt; User Configuration. The username should match a user logon in CRM.&lt;br /&gt;
    Enabling the full CRM sql logs may be useful, as the username being used by CRM will appear in the logs.&lt;br /&gt;
    IIS Failed Request tracing can be used to identify the source of HTTP error codes (401, 404, 403 etc) returned from IIS.&lt;br /&gt;
    More information is available here: http://support.microsoft.com/kb/942078&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=259</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=259"/>
		<updated>2015-08-25T11:24:34Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
Finally rebuild the &#039;CRMEmailPhoneData&#039; table&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/11716/32118.aspx#32118&lt;br /&gt;
&lt;br /&gt;
exec populate_CRMEmailPhoneData&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Tomcat&amp;diff=258</id>
		<title>Tomcat</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Tomcat&amp;diff=258"/>
		<updated>2015-08-05T08:10:41Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Easiest option here is to re-install (actually select the upgrade option) a patch and this usually works. &lt;br /&gt;
&lt;br /&gt;
Latest guide (7.3)&lt;br /&gt;
&lt;br /&gt;
https://community.sagecrm.com/knowledgebase/w/onpremisekba/1074.632-17360-sage-crm-interactive-dashboard-support-guide.aspx#CommonErrors&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Java versions later than&lt;br /&gt;
&lt;br /&gt;
version 6 update 27&lt;br /&gt;
&lt;br /&gt;
will cause issues (tomcat wont work and the report export might error out with &amp;quot;win 32 code 1 incorrect function&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
use this too test the version of java on the machine&lt;br /&gt;
&lt;br /&gt;
http://www.javatester.org/version.html&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Troubleshooting:&lt;br /&gt;
&lt;br /&gt;
1. Ensure parent paths is set to true for ASP&lt;br /&gt;
&lt;br /&gt;
..details are being investigated still&lt;br /&gt;
&lt;br /&gt;
ISAPI Rewriting&lt;br /&gt;
&lt;br /&gt;
*IIS 6 only seems to need the file mentioned in 1 below&lt;br /&gt;
1. Sage use a file called &amp;quot;....Sage\CRM\Services\IISUtils\CRMRewriter\ISAPI_Rewrite.dll&amp;quot; which is created by &amp;quot;Helicon&amp;quot; (http://www.isapirewrite.com/)&lt;br /&gt;
&lt;br /&gt;
2. The rewriting rules are written in &amp;quot;....Sage\CRM\Services\IISUtils\CRMRewriter\CRM.Rewriter.rules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
3. Re-writing essentially maps urls such as &amp;quot;http://localhost/sdata/crm71sp2j/layout/-/$service/&amp;quot; to &amp;quot;http://localhost:10009/crm71j/..etc&amp;quot;. So you can see that the port is 10009 and this is the port that TOMCAT is working through.&lt;br /&gt;
&lt;br /&gt;
404&#039;s usually appear when the &amp;quot;RewriterModule&amp;quot; is missing from IIS&lt;br /&gt;
&lt;br /&gt;
This should be added to IIS. To do this select the application (or main node) and select &amp;quot;Modules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
From there click &amp;quot;Add Managed Modules&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Set the name to be &amp;quot;RewriterModule&amp;quot;&lt;br /&gt;
&lt;br /&gt;
and the type to be &amp;quot;ManagedFusion.Rewriter.RewriterModule, ManagedFusion.Rewriter&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Note that this should map the setting in the web.config file&lt;br /&gt;
&lt;br /&gt;
		&amp;lt;httpModules&amp;gt;&lt;br /&gt;
			&amp;lt;add name=&amp;quot;RewriterModule&amp;quot; type=&amp;quot;ManagedFusion.Rewriter.RewriterModule, ManagedFusion.Rewriter&amp;quot; /&amp;gt;&lt;br /&gt;
		&amp;lt;/httpModules&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do not check the &amp;quot;Invoke only for requests to ASP.Net applications or Managed handlers&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Useful articles:&lt;br /&gt;
&lt;br /&gt;
http://aspnet.4guysfromrolla.com/articles/011404-1.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Dashboard not working outside of intranet&lt;br /&gt;
&lt;br /&gt;
The rewriter&#039;s probably trying to send the request to Tomcat to the external IP. &lt;br /&gt;
&lt;br /&gt;
In v7.1, It will look something like this, for a static IP of 50.57.215.216:&lt;br /&gt;
&lt;br /&gt;
Initial request:&lt;br /&gt;
&lt;br /&gt;
  http:// 50.57.215.216/sdata/crmj/layout/-/$service/lockrecord?tableName=LPLayout&amp;amp;id=6010&amp;amp;SID=47373617139422&amp;amp;contextEntityId=-1&amp;amp;contextRecordId=-1&lt;br /&gt;
&lt;br /&gt;
This is rewritten to:&lt;br /&gt;
&lt;br /&gt;
  http:// 50.57.215.216:10009/crmj/layout/-/$service/lockrecord?tableName=LPLayout&amp;amp;id=6010&amp;amp;SID=47373617139422&amp;amp;contextEntityId=-1&amp;amp;contextRecordId=-1&lt;br /&gt;
&lt;br /&gt;
The Tomcat port is unlikely to be accessible using the static IP. &lt;br /&gt;
The usual way I&#039;d suggest working around this is to use a fully-qualified name, and add an entry to the server&#039;s hosts file so that the FQDN will resolve to 127.0.0.1. &lt;br /&gt;
I would not suggest opening the Tomcat port for requests using the static IP.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/t/9983.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Seen on 7.2&lt;br /&gt;
&lt;br /&gt;
If you move installs you can get issues with the mail merge (dashboard might still work) if you dont have the same &#039;javapath&#039; set in custom_sysparams&lt;br /&gt;
&lt;br /&gt;
Sample code to fix this&lt;br /&gt;
&lt;br /&gt;
  update custom_sysparams&lt;br /&gt;
    set parm_value=&#039;C:\Program Files (x86)\Sage\CRM\Services\JRE\jre7\bin\&#039;&lt;br /&gt;
       where parm_name=&#039;javapath&#039;&lt;br /&gt;
&lt;br /&gt;
The error might be reported as &lt;br /&gt;
&lt;br /&gt;
  com.sage.crm.web.exception.SageAsyncProcessException: Mailmerge generation failed&lt;br /&gt;
  Caused by: com.sage.crm.core.exception.SageEndpointException: java.io.IOException: Cannot run program&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
7.2b seems to need port 11009 (used to be 10009) to be open for external ips to get access to the dashboard&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Configuration&amp;diff=257</id>
		<title>Configuration</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Configuration&amp;diff=257"/>
		<updated>2015-07-15T08:37:03Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Error - IP Address Mismatch &lt;br /&gt;
&lt;br /&gt;
Log on to the server and open regedit and the CRM settings&lt;br /&gt;
&lt;br /&gt;
Change the key value &amp;quot;IPAddressChecking&amp;quot; to be N&lt;br /&gt;
&lt;br /&gt;
IIS needs to be reset for the change to take effect&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you install SQL Express the system will setup a default sa password as&lt;br /&gt;
&lt;br /&gt;
  SageCRMv71&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/user_community/f/84/p/6017/22204.aspx#22204&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To expose emailtemplates to CRM run the following update in SQL&lt;br /&gt;
&lt;br /&gt;
  update Custom_Tables&lt;br /&gt;
    set Bord_Hidden=null&lt;br /&gt;
    where Bord_Name=&#039;EmailTemplates&#039;&lt;br /&gt;
&lt;br /&gt;
and then reload metadata (or restart IIS)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
HTTP 403.14 Forbidden Error &lt;br /&gt;
&lt;br /&gt;
This can happen in CRM with development of custom pages especially when changing from admin mode to Normal user mode&lt;br /&gt;
&lt;br /&gt;
A work around to top this happening is to create a default page in the &amp;quot;CRM/custompages&amp;quot; folder&lt;br /&gt;
&lt;br /&gt;
This page redirects the user to some location (our example goes to action 183. &lt;br /&gt;
&lt;br /&gt;
  var newUrl=CRM.Url(183);&lt;br /&gt;
  Response.Redirect(newUrl);&lt;br /&gt;
&lt;br /&gt;
Within IIS you have to add your file name as a default document at the custompages folder level&lt;br /&gt;
&lt;br /&gt;
[[File:403index.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Ref: https://support.na.sage.com/selfservice/viewContent.do?externalId=39716&amp;amp;sliceId=1&lt;br /&gt;
&lt;br /&gt;
Description&lt;br /&gt;
	&lt;br /&gt;
How to configure CRM 7.2 for IIS Auto Login&lt;br /&gt;
Resolution&lt;br /&gt;
	&lt;br /&gt;
&lt;br /&gt;
    Open the IIS Manager&lt;br /&gt;
    Click on the CRM site&lt;br /&gt;
    Click Basic Settings&lt;br /&gt;
    Set the Connect As setting to &#039;Application User (Pass-through Authentication)&#039;&lt;br /&gt;
    Click on the CRM site&lt;br /&gt;
    Open the Authentication inteface&lt;br /&gt;
    Enable Anonymous and Windows Authentication&lt;br /&gt;
    Select Anonymous Authentication and click Edit&lt;br /&gt;
    Set the Anonymous Authentication to use the Application Pool Identity&lt;br /&gt;
    Open Internet Explorer and log in to CRM&lt;br /&gt;
    Setup all your user accounts so that the usernames matches the usernames Active Directory&lt;br /&gt;
    Click Administration, Users, User Configuration&lt;br /&gt;
    Click Change&lt;br /&gt;
    Set IIS Auto Login to Yes&lt;br /&gt;
    Set the Default Domain for IIS Auto Login to match your Windows Domain&lt;br /&gt;
    Open SQL Management Studio&lt;br /&gt;
    Click New Query&lt;br /&gt;
    use [CRM Databasename]&lt;br /&gt;
    go&lt;br /&gt;
    update users set user_password = NULL&lt;br /&gt;
    Do an IISReset&lt;br /&gt;
    Open Internet Explorer&lt;br /&gt;
    Go to Internet Options&lt;br /&gt;
    Add the CRM site to Trusted Sites&lt;br /&gt;
    Click the Custom Level option under Security&lt;br /&gt;
    Under User Authentication, set the option to &#039;Automatic Logon with Current Username and Password&#039;&lt;br /&gt;
    Repeat step 19-23 on all workstations&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=256</id>
		<title>Screen Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=256"/>
		<updated>2015-06-25T13:33:12Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
To add in script code from a page set the link as follows&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;script src=&amp;quot;../custompages/pathtofile/commlist.js&amp;quot; type=&amp;quot;text/javascript&amp;quot; language=&amp;quot;JavaScript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To enumerate block entries (Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/11/28/setting-screen-properties-within-a-multiblock-asp-page-using-the-com-api.aspx)&lt;br /&gt;
&lt;br /&gt;
  //Set EntryBlock properties for an EntryGroup Block using an Enumerator&lt;br /&gt;
  var myE = new Enumerator(myBlock);&lt;br /&gt;
  while (!myE.atEnd())&lt;br /&gt;
  {&lt;br /&gt;
     myEntryBlock = myE.item();&lt;br /&gt;
     myEntryBlock.ReadOnly = false;&lt;br /&gt;
     myEntryBlock.Required = false;&lt;br /&gt;
     myE.moveNext();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Useful menthod to parse the querystring from the client&lt;br /&gt;
&lt;br /&gt;
Ref: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx&lt;br /&gt;
&lt;br /&gt;
  function getQuerystring(key, default_)&lt;br /&gt;
  {&lt;br /&gt;
    if (default_==null) default_=&amp;quot;&amp;quot;;&lt;br /&gt;
    key = key.replace(/[\[]/,&amp;quot;\\\[&amp;quot;).replace(/[\]]/,&amp;quot;\\\]&amp;quot;);&lt;br /&gt;
    var regex = new RegExp(&amp;quot;[\\?&amp;amp;]&amp;quot;+key+&amp;quot;=([^&amp;amp;#]*)&amp;quot;);&lt;br /&gt;
    var qs = regex.exec(window.location.href);&lt;br /&gt;
    if(qs == null)&lt;br /&gt;
      return default_;&lt;br /&gt;
    else&lt;br /&gt;
      return qs[1];&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To break up a screen visually create a dummy field and add in&lt;br /&gt;
&lt;br /&gt;
  &amp;amp;lt;HR border=1&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
as the caption&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Adding new phone and email addresses to screens&lt;br /&gt;
&lt;br /&gt;
Go into translations and look up Link_CompPhon (or link_prefixphone/email)&lt;br /&gt;
&lt;br /&gt;
This shows you a list which you can add to by adding new translations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Custom validation on a screen&lt;br /&gt;
&lt;br /&gt;
If you have a custom method for validating data and you wish to code this in your ASP page (or outside of the validation script area) then you need to do something like the following&lt;br /&gt;
&lt;br /&gt;
  Entry = ctproductblock.GetEntry(&amp;quot;productname&amp;quot;);&lt;br /&gt;
  if(!validate(Request.Form(&amp;quot;productcode&amp;quot;)))&lt;br /&gt;
  {					&lt;br /&gt;
      Entry.ValidateScript = &amp;quot;Valid=false;ErrorStr=&#039;Product code already exists&#039;;&amp;quot;; &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
if our sample above the validate() method checks that the product code is unique.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/07/22/server-side-validation-and-asp-pages.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Add a hyper link to a field on a screen - Custom SSA fields can only be hyperlinked throught the UI for lists and not for screens so here we have a workaround.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2010/07/06/hyperlinking-to-a-parent-custom-entity-from-a-search-select-advanced-field.aspx&lt;br /&gt;
&lt;br /&gt;
*Within CRM open the screen&lt;br /&gt;
*Select the field&lt;br /&gt;
*Within the &amp;quot;create script&amp;quot; textbox enter in the following (update as per your custom entity first)&lt;br /&gt;
&lt;br /&gt;
  var intRecordId = CRM.GetContextInfo(&amp;quot;opportunity&amp;quot;,&amp;quot;oppo_projectid&amp;quot;);&lt;br /&gt;
  var strURL = CRM.URL(&amp;quot;project/projectsummary.asp&amp;quot;)+&amp;quot;&amp;amp;proj_projectid=&amp;quot;+intRecordId;&lt;br /&gt;
  var strCaptionText = &amp;quot;Project&amp;quot;;&lt;br /&gt;
  var strFullCaption = &amp;quot;&amp;lt;a href=&amp;quot;+strURL+&amp;quot;&amp;gt;&amp;quot;+strCaptionText+&amp;quot;&amp;lt;/a&amp;gt;:&amp;quot;;&lt;br /&gt;
  Caption = strFullCaption;&lt;br /&gt;
&lt;br /&gt;
This sets the field &amp;quot;Caption&amp;quot; to be a hyperlink so it is not ideal but works as a quick &amp;quot;fix&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Field Validate scripts - Values vs values - (seen in 7.1)&lt;br /&gt;
&lt;br /&gt;
This threw me a few times....within field validate scripts the &amp;quot;values&amp;quot; object starts with a lowercase v&lt;br /&gt;
&lt;br /&gt;
  ErrorStr=&amp;quot;testx=&amp;quot;+values(&amp;quot;case_ct_supportemail&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Anything in values only comes from the screen so if the field referenced is not on the screen then it wont be in values - you would then query the db to get that value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=255</id>
		<title>List Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=255"/>
		<updated>2015-06-25T09:55:50Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Client-side function to clear out empty rows on a table (tested in 7.1 only)&lt;br /&gt;
&lt;br /&gt;
-Makes an assumption about the first Td being empty&lt;br /&gt;
&lt;br /&gt;
  function clearEmpptyTableRows()&lt;br /&gt;
  {&lt;br /&gt;
    var trcol=document.getElementsByTagName(&amp;quot;TR&amp;quot;);&lt;br /&gt;
    for (var i=1;i&amp;lt;trcol.length;i++)&lt;br /&gt;
    {&lt;br /&gt;
      //get the first td&lt;br /&gt;
      var _td=trcol[i].childNodes[0];&lt;br /&gt;
      if (_td!=null){&lt;br /&gt;
           if ((_td.innerHTML==&amp;quot;&amp;quot;)||(_td.innerHTML==null)||(_td.innerHTML==&amp;quot;&amp;amp;nbsp;&amp;quot;)){&lt;br /&gt;
                if ((_td.className==&#039;ROW2&#039;)||(_td.className==&#039;ROW1&#039;)){&lt;br /&gt;
                  trcol[i].style.visibility=&#039;hidden&#039;;&lt;br /&gt;
                  trcol[i].style.display=&#039;none&#039;;&lt;br /&gt;
                }&lt;br /&gt;
           }else{&lt;br /&gt;
               //console.log(i+&amp;quot;-&amp;quot;+_td.innerText);&lt;br /&gt;
               //console.log(i+&amp;quot;-&amp;quot;+_td.innerHTML);&lt;br /&gt;
           }&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=254</id>
		<title>List Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=254"/>
		<updated>2015-06-25T09:55:30Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Client-side function to clear out empty rows on a table (tested in 7.1 only)&lt;br /&gt;
&lt;br /&gt;
-Makes an assumption about the first Td being empty&lt;br /&gt;
&lt;br /&gt;
  function clearEmpptyTableRows()&lt;br /&gt;
  {&lt;br /&gt;
    var trcol=document.getElementsByTagName(&amp;quot;TR&amp;quot;);&lt;br /&gt;
    for (var i=1;i&amp;lt;trcol.length;i++)&lt;br /&gt;
    {&lt;br /&gt;
      //get the first td&lt;br /&gt;
      var _td=trcol[i].childNodes[0];&lt;br /&gt;
      if (_td!=null){&lt;br /&gt;
           if ((_td.innerHTML==&amp;quot;&amp;quot;)||(_td.innerHTML==null)||(_td.innerHTML==&amp;quot;&amp;amp;nbsp;&amp;quot;)){&lt;br /&gt;
                if ((_td.className==&#039;ROW2&#039;)||(_td.className==&#039;ROW1&#039;)){&lt;br /&gt;
                  trcol[i].style.visibility=&#039;hidden&#039;;&lt;br /&gt;
                  trcol[i].style.display=&#039;none&#039;;&lt;br /&gt;
                }&lt;br /&gt;
           }else{&lt;br /&gt;
               //console.log(i+&amp;quot;-&amp;quot;+_td.innerText);&lt;br /&gt;
               //console.log(i+&amp;quot;-&amp;quot;+_td.innerHTML);&lt;br /&gt;
	  }&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=253</id>
		<title>List Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=253"/>
		<updated>2015-06-25T09:54:17Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Client-side function to clear out empty rows on a table (tested in 7.1 only)&lt;br /&gt;
&lt;br /&gt;
-Makes an assumption about the first Td being empty&lt;br /&gt;
&lt;br /&gt;
  function clearEmpptyTableRows()&lt;br /&gt;
  {&lt;br /&gt;
    var trcol=document.getElementsByTagName(&amp;quot;TR&amp;quot;);&lt;br /&gt;
    for (var i=1;i&amp;lt;trcol.length;i++)&lt;br /&gt;
    {&lt;br /&gt;
      //get the first td&lt;br /&gt;
      var _td=trcol[i].childNodes[0];&lt;br /&gt;
      if (_td!=null){&lt;br /&gt;
           if ((_td.innerHTML==&amp;quot;&amp;quot;)||(_td.innerHTML==null)||(_td.innerHTML==&amp;quot;&amp;amp;nbsp;&amp;quot;)){&lt;br /&gt;
                if ((_td.className==&#039;ROW2&#039;)||(_td.className==&#039;ROW1&#039;))&lt;br /&gt;
		{&lt;br /&gt;
		  trcol[i].style.visibility=&#039;hidden&#039;;&lt;br /&gt;
		  trcol[i].style.display=&#039;none&#039;;&lt;br /&gt;
		}&lt;br /&gt;
	  }else{&lt;br /&gt;
	    //console.log(i+&amp;quot;-&amp;quot;+_td.innerText);&lt;br /&gt;
		 //console.log(i+&amp;quot;-&amp;quot;+_td.innerHTML);&lt;br /&gt;
	  }&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=252</id>
		<title>List Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=252"/>
		<updated>2015-06-25T09:53:38Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Client-side function to clear out empty rows on a table (tested in 7.1 only)&lt;br /&gt;
&lt;br /&gt;
-Makes an assumption about the first Td being empty&lt;br /&gt;
&lt;br /&gt;
  function clearEmpptyTableRows()&lt;br /&gt;
  {&lt;br /&gt;
    var trcol=document.getElementsByTagName(&amp;quot;TR&amp;quot;);&lt;br /&gt;
    for (var i=1;i&amp;lt;trcol.length;i++)&lt;br /&gt;
    {&lt;br /&gt;
      //get the first td&lt;br /&gt;
      var _td=trcol[i].childNodes[0];&lt;br /&gt;
      if (_td!=null){&lt;br /&gt;
	  if ((_td.innerHTML==&amp;quot;&amp;quot;)||(_td.innerHTML==null)||(_td.innerHTML==&amp;quot;&amp;amp;nbsp;&amp;quot;)){&lt;br /&gt;
		if ((_td.className==&#039;ROW2&#039;)||(_td.className==&#039;ROW1&#039;))&lt;br /&gt;
		{&lt;br /&gt;
		  trcol[i].style.visibility=&#039;hidden&#039;;&lt;br /&gt;
		  trcol[i].style.display=&#039;none&#039;;&lt;br /&gt;
		}&lt;br /&gt;
	  }else{&lt;br /&gt;
	    //console.log(i+&amp;quot;-&amp;quot;+_td.innerText);&lt;br /&gt;
		 //console.log(i+&amp;quot;-&amp;quot;+_td.innerHTML);&lt;br /&gt;
	  }&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=251</id>
		<title>List Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=List_Customisation&amp;diff=251"/>
		<updated>2015-06-25T09:52:43Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: Created page with &amp;quot; Client-side function to clear out empty rows on a table (tested in 7.1 only)  -Makes an assumption about the first Td being empty  function clearEmpptyTableRows() {  var trco...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Client-side function to clear out empty rows on a table (tested in 7.1 only)&lt;br /&gt;
&lt;br /&gt;
-Makes an assumption about the first Td being empty&lt;br /&gt;
&lt;br /&gt;
function clearEmpptyTableRows()&lt;br /&gt;
{&lt;br /&gt;
 var trcol=document.getElementsByTagName(&amp;quot;TR&amp;quot;);&lt;br /&gt;
  &lt;br /&gt;
  for (var i=1;i&amp;lt;trcol.length;i++)&lt;br /&gt;
  {&lt;br /&gt;
    //get the first td&lt;br /&gt;
	var _td=trcol[i].childNodes[0];&lt;br /&gt;
	if (_td!=null)&lt;br /&gt;
	{&lt;br /&gt;
	&lt;br /&gt;
	  if ((_td.innerHTML==&amp;quot;&amp;quot;)||(_td.innerHTML==null)||(_td.innerHTML==&amp;quot;&amp;amp;nbsp;&amp;quot;))&lt;br /&gt;
	  {&lt;br /&gt;
		if ((_td.className==&#039;ROW2&#039;)||(_td.className==&#039;ROW1&#039;))&lt;br /&gt;
		{&lt;br /&gt;
		  trcol[i].style.visibility=&#039;hidden&#039;;&lt;br /&gt;
		  trcol[i].style.display=&#039;none&#039;;&lt;br /&gt;
		}&lt;br /&gt;
	  }else{&lt;br /&gt;
	    //console.log(i+&amp;quot;-&amp;quot;+_td.innerText);&lt;br /&gt;
		 //console.log(i+&amp;quot;-&amp;quot;+_td.innerHTML);&lt;br /&gt;
	  }&lt;br /&gt;
	}&lt;br /&gt;
  }&lt;br /&gt;
}&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=250</id>
		<title>Screen Customisation</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Screen_Customisation&amp;diff=250"/>
		<updated>2015-06-25T08:41:54Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
To add in script code from a page set the link as follows&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;script src=&amp;quot;../custompages/pathtofile/commlist.js&amp;quot; type=&amp;quot;text/javascript&amp;quot; language=&amp;quot;JavaScript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To enumerate block entries (Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/11/28/setting-screen-properties-within-a-multiblock-asp-page-using-the-com-api.aspx)&lt;br /&gt;
&lt;br /&gt;
  //Set EntryBlock properties for an EntryGroup Block using an Enumerator&lt;br /&gt;
  var myE = new Enumerator(myBlock);&lt;br /&gt;
  while (!myE.atEnd())&lt;br /&gt;
  {&lt;br /&gt;
     myEntryBlock = myE.item();&lt;br /&gt;
     myEntryBlock.ReadOnly = false;&lt;br /&gt;
     myEntryBlock.Required = false;&lt;br /&gt;
     myE.moveNext();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Useful menthod to parse the querystring from the client&lt;br /&gt;
&lt;br /&gt;
Ref: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx&lt;br /&gt;
&lt;br /&gt;
  function getQuerystring(key, default_)&lt;br /&gt;
  {&lt;br /&gt;
    if (default_==null) default_=&amp;quot;&amp;quot;;&lt;br /&gt;
    key = key.replace(/[\[]/,&amp;quot;\\\[&amp;quot;).replace(/[\]]/,&amp;quot;\\\]&amp;quot;);&lt;br /&gt;
    var regex = new RegExp(&amp;quot;[\\?&amp;amp;]&amp;quot;+key+&amp;quot;=([^&amp;amp;#]*)&amp;quot;);&lt;br /&gt;
    var qs = regex.exec(window.location.href);&lt;br /&gt;
    if(qs == null)&lt;br /&gt;
      return default_;&lt;br /&gt;
    else&lt;br /&gt;
      return qs[1];&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
To break up a screen visually create a dummy field and add in&lt;br /&gt;
&lt;br /&gt;
  &amp;amp;lt;HR border=1&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
as the caption&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Adding new phone and email addresses to screens&lt;br /&gt;
&lt;br /&gt;
Go into translations and look up Link_CompPhon (or link_prefixphone/email)&lt;br /&gt;
&lt;br /&gt;
This shows you a list which you can add to by adding new translations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Custom validation on a screen&lt;br /&gt;
&lt;br /&gt;
If you have a custom method for validating data and you wish to code this in your ASP page (or outside of the validation script area) then you need to do something like the following&lt;br /&gt;
&lt;br /&gt;
  Entry = ctproductblock.GetEntry(&amp;quot;productname&amp;quot;);&lt;br /&gt;
  if(!validate(Request.Form(&amp;quot;productcode&amp;quot;)))&lt;br /&gt;
  {					&lt;br /&gt;
      Entry.ValidateScript = &amp;quot;Valid=false;ErrorStr=&#039;Product code already exists&#039;;&amp;quot;; &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
if our sample above the validate() method checks that the product code is unique.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2007/07/22/server-side-validation-and-asp-pages.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Add a hyper link to a field on a screen - Custom SSA fields can only be hyperlinked throught the UI for lists and not for screens so here we have a workaround.&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2010/07/06/hyperlinking-to-a-parent-custom-entity-from-a-search-select-advanced-field.aspx&lt;br /&gt;
&lt;br /&gt;
*Within CRM open the screen&lt;br /&gt;
*Select the field&lt;br /&gt;
*Within the &amp;quot;create script&amp;quot; textbox enter in the following (update as per your custom entity first)&lt;br /&gt;
&lt;br /&gt;
  var intRecordId = CRM.GetContextInfo(&amp;quot;opportunity&amp;quot;,&amp;quot;oppo_projectid&amp;quot;);&lt;br /&gt;
  var strURL = CRM.URL(&amp;quot;project/projectsummary.asp&amp;quot;)+&amp;quot;&amp;amp;proj_projectid=&amp;quot;+intRecordId;&lt;br /&gt;
  var strCaptionText = &amp;quot;Project&amp;quot;;&lt;br /&gt;
  var strFullCaption = &amp;quot;&amp;lt;a href=&amp;quot;+strURL+&amp;quot;&amp;gt;&amp;quot;+strCaptionText+&amp;quot;&amp;lt;/a&amp;gt;:&amp;quot;;&lt;br /&gt;
  Caption = strFullCaption;&lt;br /&gt;
&lt;br /&gt;
This sets the field &amp;quot;Caption&amp;quot; to be a hyperlink so it is not ideal but works as a quick &amp;quot;fix&amp;quot;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=249</id>
		<title>Javascript</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=249"/>
		<updated>2015-05-07T14:20:25Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Useful ASP javascript code to see all &amp;quot;Request.ServerVariables&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Could also be used on &amp;quot;Request.Form&amp;quot; etc&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.ServerVariables()); !f.atEnd(); f.moveNext()) &lt;br /&gt;
    { &lt;br /&gt;
        var x = f.item(); &lt;br /&gt;
        Response.Write(&amp;quot;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.ServerVariables(x)); &lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
For Request form&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.Form()); !f.atEnd(); f.moveNext())&lt;br /&gt;
    { &lt;br /&gt;
      var x = f.item(); &lt;br /&gt;
      Response.Write(&amp;quot;&amp;lt;br&amp;gt;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.Form(x));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Client side DOM - enumerate all checkboxes and set them as checked&lt;br /&gt;
&lt;br /&gt;
  var _cb=document.getElementsByTagName(&amp;quot;input&amp;quot;);&lt;br /&gt;
  for(var i=0;i&amp;lt;_cb.length;i++)&lt;br /&gt;
  {&lt;br /&gt;
    var box=_cb[i];&lt;br /&gt;
	if (box.type==&amp;quot;checkbox&amp;quot;)&lt;br /&gt;
	  box.checked=true;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful update from Jeff Richards regarding compressing javascript &lt;br /&gt;
&lt;br /&gt;
http://jscompress.com/&lt;br /&gt;
&lt;br /&gt;
http://javascriptcompressor.com/&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2013/12/31/sage-crm-7-2-adding-protection-to-your-code-in-script-libraries.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful sites&lt;br /&gt;
&lt;br /&gt;
  http://devdocs.io/javascript/&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
FileSystemObject - read a file on the server&lt;br /&gt;
&lt;br /&gt;
  function readFile(filename){&lt;br /&gt;
    var fso = new ActiveXObject(&amp;quot;Scripting.FileSystemObject&amp;quot;);&lt;br /&gt;
    var ForReading = 1;&lt;br /&gt;
    var f1 = fso.OpenTextFile(filename, ForReading);&lt;br /&gt;
    var text = f1.ReadAll();&lt;br /&gt;
    f1.close();&lt;br /&gt;
    return text;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
--you might need the path the ASP page is on&lt;br /&gt;
&lt;br /&gt;
  var pageroot=Request.ServerVariables(&amp;quot;APPL_PHYSICAL_PATH&amp;quot;);&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=ASP&amp;diff=248</id>
		<title>ASP</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=ASP&amp;diff=248"/>
		<updated>2015-04-22T09:06:15Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Cannot see the error messages in IIS&lt;br /&gt;
&lt;br /&gt;
  You can configure these settings by using IIS Manager. To do so, open IIS Manager and navigate to the site or application where you want to enable or disable script messages, and then double-click the ASP feature.&lt;br /&gt;
&lt;br /&gt;
  In the list of ASP features, configure the Script Error Message and Send Errors To Browser options.&lt;br /&gt;
&lt;br /&gt;
Ref: http://learn.iis.net/page.aspx/564/classic-asp-script-error-messages-no-longer-shown-in-web-browser-by-default/&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Cannot create automation object - Issue caused by the eware.dll not being registered correctly&lt;br /&gt;
&lt;br /&gt;
Instruction to manually swap in a new eware.dll&lt;br /&gt;
&lt;br /&gt;
    #Stop the IIS server.&lt;br /&gt;
    #Backup the existing CRM eWare.dll and database, rename the eWare.dll file.&lt;br /&gt;
    #Copy the interim patch eWare.dll to the CRM directory.&lt;br /&gt;
    #Register the new eWare.dll by using regsvr32.exe.e.g. regsvr32 &amp;quot;C:\Program Files\Sage\CRM\\WWWRoot\eWare.dll&amp;quot;&lt;br /&gt;
    #Restart the IIS server. &lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2008/02/06/patches-and-service-packs-and-registering-the-eware-dll.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Nice details here on how to use security in ASP pages&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2009/02/10/more-about-using-crm-security-in-asp-pages.aspx&lt;br /&gt;
&lt;br /&gt;
Basically you use the CRM.Button API&lt;br /&gt;
&lt;br /&gt;
  if (!CRM.Button(&amp;quot;caption&amp;quot;,&amp;quot;image.gif&amp;quot;, &amp;quot;url.asp&amp;quot;,&amp;quot;COMPANY&amp;quot;,&amp;quot;EDIT&amp;quot;)) &lt;br /&gt;
  {&lt;br /&gt;
    ...so something&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Parameters 	&lt;br /&gt;
&lt;br /&gt;
1. Caption: The caption for the button. This is translated based on the user&#039;s language (providing there is a matching entry in CRM Translations).&lt;br /&gt;
&lt;br /&gt;
2. ImageName: The image you want displayed on the button. All images need to be stored in the CRM directory &#039;Img&#039; folder.&lt;br /&gt;
&lt;br /&gt;
3. URL: The URL that this button links to. This can either be a link to a Web address or to a custom page in the CRM custom pages folder. (See URL below).&lt;br /&gt;
&lt;br /&gt;
4. PermissionsEntity: PermissionsEntity is the name of the entity. &lt;br /&gt;
&lt;br /&gt;
5. PermissionsType is either VIEW, EDIT, DELETE or INSERT, depending on the action of the button.&lt;br /&gt;
&lt;br /&gt;
6. Target: This allows the TARGET property of the button&#039;s anchor () tag to be set. &lt;br /&gt;
&lt;br /&gt;
API Ref: https://community.sagecrm.com/developerhelp/Content/Developer/ASP%20Object%20Reference/CRMBase%20Object/AS_CRMBaseButton.htm?SearchType=Stem&amp;amp;Highlight=buttons|Button|button|Buttons&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
To Enumerate the columns in a crm record object you can do the following:&lt;br /&gt;
&lt;br /&gt;
  var myE = new Enumerator(recordObj);	&lt;br /&gt;
  while (!myE.atEnd()) {&lt;br /&gt;
    var nm=myE.item();&lt;br /&gt;
    //...do seomthing&lt;br /&gt;
    myE.moveNext();  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Code to sent a message and create a communicationn in CRM&lt;br /&gt;
&lt;br /&gt;
  var myMailObject = CRM.GetBlock(&amp;quot;Messageblock&amp;quot;); &lt;br /&gt;
  with (myMailObject){ &lt;br /&gt;
  DisplayForm = false; &lt;br /&gt;
  var strEmailId=new String(ctQueueRec.ctqu_data1); &lt;br /&gt;
  if(strEmailId==&amp;quot;&amp;quot; || strEmailId==&amp;quot;undefined&amp;quot;)strEmailId=&amp;quot;&amp;quot;; &lt;br /&gt;
  if(strEmailId!=&amp;quot;&amp;quot;){ &lt;br /&gt;
  var strSubject=new String(ctQueueRec.ctqu_data2); &lt;br /&gt;
  if(strSubject==&amp;quot;&amp;quot; || strSubject==&amp;quot;undefined&amp;quot;)strSubject=&amp;quot;&amp;quot;; &lt;br /&gt;
  var strBody=new String(ctQueueRec.ctqu_data3); &lt;br /&gt;
  if(strBody==&amp;quot;&amp;quot; || strBody==&amp;quot;undefined&amp;quot;)strBody=&amp;quot;&amp;quot;; &lt;br /&gt;
  mSubject =strSubject; &lt;br /&gt;
  mBody =strBody;  &lt;br /&gt;
  AddRecipient(strEmailId,strEmailId,&amp;quot;TO&amp;quot;); &lt;br /&gt;
  Mode = 2; &lt;br /&gt;
  //CRM.AddContent(myMailObject.execute());  &lt;br /&gt;
  if (true){ &lt;br /&gt;
&lt;br /&gt;
    var RecordComm = CRM.CreateRecord(&amp;quot;Communication&amp;quot;); &lt;br /&gt;
    RecordComm.comm_action=&amp;quot;EmailOut&amp;quot;; &lt;br /&gt;
    RecordComm.comm_status=&amp;quot;Complete&amp;quot;; &lt;br /&gt;
    RecordComm.comm_priority=&amp;quot;Normal&amp;quot;; &lt;br /&gt;
    RecordComm.comm_type=&amp;quot;Task&amp;quot;; &lt;br /&gt;
    RecordComm.comm_to=strEmailId; &lt;br /&gt;
    RecordComm.comm_email=strBody; &lt;br /&gt;
    RecordComm.comm_subject=strSubject; &lt;br /&gt;
    RecordComm.comm_note=strSubject; &lt;br /&gt;
    RecordComm.comm_datetime=executiondate.getVarDate();; &lt;br /&gt;
    RecordComm.SaveChanges(); &lt;br /&gt;
    var RecordComm_Link = CRM.CreateRecord(&amp;quot;Comm_Link&amp;quot;); &lt;br /&gt;
    RecordComm_Link.CmLi_Comm_CommunicationId=RecordComm.comm_communicationid; &lt;br /&gt;
    RecordComm_Link.CmLi_Comm_UserId=1; &lt;br /&gt;
    var ipersonId=new String(ctQueueRec.ctqu_data4); &lt;br /&gt;
    if(ipersonId==&amp;quot;&amp;quot; || ipersonId==&amp;quot;undefined&amp;quot;)ipersonId=0; &lt;br /&gt;
    if(ipersonId!=0) &lt;br /&gt;
       RecordComm_Link.CmLi_Comm_PersonId=ipersonId; &lt;br /&gt;
    //RecordComm_Link.cmli_comm_companyid=strCompanyId; &lt;br /&gt;
    RecordComm_Link.SaveChanges(); &lt;br /&gt;
    Response.Write(&amp;quot;done&amp;quot;+ipersonId); &lt;br /&gt;
    } &lt;br /&gt;
    else{ &lt;br /&gt;
        Response.Write(&amp;quot;There has been a problem: &amp;quot;+mErrorMessage); &lt;br /&gt;
    } &lt;br /&gt;
    } &lt;br /&gt;
    }&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=VIES&amp;diff=247</id>
		<title>VIES</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=VIES&amp;diff=247"/>
		<updated>2015-04-22T09:05:28Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: Blanked the page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=External_Links&amp;diff=246</id>
		<title>External Links</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=External_Links&amp;diff=246"/>
		<updated>2015-04-16T12:55:19Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Developer Help&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[http://sagecity.na.sage.com/support_communities/sage_crm/default.aspx &#039;NA Sage city forum&#039;]&lt;br /&gt;
&lt;br /&gt;
[https://community.sagecrm.com/developerhelp/ &#039;Sage CRM Developer Help&#039;]&lt;br /&gt;
&lt;br /&gt;
[https://community.sagecrm.com/adminhelp/ &#039;Sage CRM Admin Help&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://help.sagecrm.com/js-api/classes/caption.html &#039;Client Side API&#039;]&lt;br /&gt;
&lt;br /&gt;
[https://community.sagecrm.com/ &#039;Sage CRM Community&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://community.sagesoftware.com/ &#039;NA Sage Community Forums&#039;]&lt;br /&gt;
&lt;br /&gt;
[http://community.sagesoftware.com/t5/Sage-Pro-ERP-Forum/bd-p/SageProERPForum &#039;Sage Pro ERP Forum&#039;]&lt;br /&gt;
&lt;br /&gt;
Useful tools&lt;br /&gt;
&lt;br /&gt;
[http://regexpal.com/ &#039;Test Regex expressions&#039;]&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Filter_screen&amp;diff=245</id>
		<title>Filter screen</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Filter_screen&amp;diff=245"/>
		<updated>2015-04-03T08:19:23Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In filter screens when you set the default value for a field you must do an IIS reset to see the result work (reloading metadata does not work - as of CRM71). &lt;br /&gt;
&lt;br /&gt;
  DefaultValue=&amp;quot;Complete&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Building Filter screens&lt;br /&gt;
&lt;br /&gt;
  Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2009/07/29/building-list-screens-with-filterboxes-take-2.aspx&lt;br /&gt;
&lt;br /&gt;
Sample code from referenced link above - shows how to build a screen with a filter (essentially its a search screen)&lt;br /&gt;
&lt;br /&gt;
  var FilterBoxBlock = eWare.GetBlock(&amp;quot;TestFilter&amp;quot;);&lt;br /&gt;
  var strFilterButton = eWare.Button(&amp;quot;filter&amp;quot;, &amp;quot;filter.gif&amp;quot;, &amp;quot;javascript:document.EntryForm.submit();&amp;quot;);&lt;br /&gt;
  FilterBoxBlock.NewLine = false;&lt;br /&gt;
  FilterBoxBlock.ButtonLocation = Bottom;&lt;br /&gt;
  FilterBoxBlock.ButtonAlignment = Left;&lt;br /&gt;
  var ListBlock = eWare.GetBlock(&amp;quot;TestList&amp;quot;);&lt;br /&gt;
  var Container = eWare.GetBlock(&amp;quot;Container&amp;quot;);&lt;br /&gt;
  Container.DisplayButton(Button_Default) = false;&lt;br /&gt;
  Container.AddBlock (ListBlock);&lt;br /&gt;
  Container.AddBlock (FilterBoxBlock); // here we are adding the filter block after the list block&lt;br /&gt;
  ListBlock.ArgObj = FilterBoxBlock;&lt;br /&gt;
  if ((Request.Form(&#039;HIDDENSCROLLMODE&#039;) != &#039;2&#039;) &amp;amp;&amp;amp; (Request.Form(&#039;HIDDENSCROLLMODE&#039;) != &#039;3&#039;)) &lt;br /&gt;
  {&lt;br /&gt;
     Container.Execute(); // This is the first execute which we drop.&lt;br /&gt;
  }&lt;br /&gt;
  FilterBoxBlock.AddButton(strFilterButton);&lt;br /&gt;
  eWare.AddContent(Container.Execute());&lt;br /&gt;
  Response.Write(eWare.GetPage());&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Filter_screen&amp;diff=244</id>
		<title>Filter screen</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Filter_screen&amp;diff=244"/>
		<updated>2015-04-03T08:18:33Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In filter screens when you set the default value for a field you must do an IIS reset to see the result work (reloading metadata does not work - as of CRM71). &lt;br /&gt;
&lt;br /&gt;
  DefaultValue=&amp;quot;Complete&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Building Filter screens&lt;br /&gt;
&lt;br /&gt;
  Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2009/07/29/building-list-screens-with-filterboxes-take-2.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  var FilterBoxBlock = eWare.GetBlock(&amp;quot;TestFilter&amp;quot;);&lt;br /&gt;
  var strFilterButton = eWare.Button(&amp;quot;filter&amp;quot;, &amp;quot;filter.gif&amp;quot;, &amp;quot;javascript:document.EntryForm.submit();&amp;quot;);&lt;br /&gt;
  FilterBoxBlock.NewLine = false;&lt;br /&gt;
  FilterBoxBlock.ButtonLocation = Bottom;&lt;br /&gt;
  FilterBoxBlock.ButtonAlignment = Left;&lt;br /&gt;
  var ListBlock = eWare.GetBlock(&amp;quot;TestList&amp;quot;);&lt;br /&gt;
  var Container = eWare.GetBlock(&amp;quot;Container&amp;quot;);&lt;br /&gt;
  Container.DisplayButton(Button_Default) = false;&lt;br /&gt;
  Container.AddBlock (ListBlock);&lt;br /&gt;
  Container.AddBlock (FilterBoxBlock); // here we are adding the filter block after the list block&lt;br /&gt;
  ListBlock.ArgObj = FilterBoxBlock;&lt;br /&gt;
  if ((Request.Form(&#039;HIDDENSCROLLMODE&#039;) != &#039;2&#039;) &amp;amp;&amp;amp; (Request.Form(&#039;HIDDENSCROLLMODE&#039;) != &#039;3&#039;)) &lt;br /&gt;
  {&lt;br /&gt;
     Container.Execute(); // This is the first execute which we drop.&lt;br /&gt;
  }&lt;br /&gt;
  FilterBoxBlock.AddButton(strFilterButton);&lt;br /&gt;
  eWare.AddContent(Container.Execute());&lt;br /&gt;
  Response.Write(eWare.GetPage());&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=243</id>
		<title>Javascript</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=243"/>
		<updated>2015-03-09T11:16:30Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Useful ASP javascript code to see all &amp;quot;Request.ServerVariables&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Could also be used on &amp;quot;Request.Form&amp;quot; etc&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.ServerVariables()); !f.atEnd(); f.moveNext()) &lt;br /&gt;
    { &lt;br /&gt;
        var x = f.item(); &lt;br /&gt;
        Response.Write(&amp;quot;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.ServerVariables(x)); &lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
For Request form&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.Form()); !f.atEnd(); f.moveNext())&lt;br /&gt;
    { &lt;br /&gt;
      var x = f.item(); &lt;br /&gt;
      Response.Write(&amp;quot;&amp;lt;br&amp;gt;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.Form(x));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Client side DOM - enumerate all checkboxes and set them as checked&lt;br /&gt;
&lt;br /&gt;
  var _cb=document.getElementsByTagName(&amp;quot;input&amp;quot;);&lt;br /&gt;
  for(var i=0;i&amp;lt;_cb.length;i++)&lt;br /&gt;
  {&lt;br /&gt;
    var box=_cb[i];&lt;br /&gt;
	if (box.type==&amp;quot;checkbox&amp;quot;)&lt;br /&gt;
	  box.checked=true;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful update from Jeff Richards regarding compressing javascript &lt;br /&gt;
&lt;br /&gt;
http://jscompress.com/&lt;br /&gt;
&lt;br /&gt;
http://javascriptcompressor.com/&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2013/12/31/sage-crm-7-2-adding-protection-to-your-code-in-script-libraries.aspx&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful sites&lt;br /&gt;
&lt;br /&gt;
  http://devdocs.io/javascript/&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=242</id>
		<title>Javascript</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=Javascript&amp;diff=242"/>
		<updated>2015-03-09T11:16:00Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Useful ASP javascript code to see all &amp;quot;Request.ServerVariables&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Could also be used on &amp;quot;Request.Form&amp;quot; etc&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.ServerVariables()); !f.atEnd(); f.moveNext()) &lt;br /&gt;
    { &lt;br /&gt;
        var x = f.item(); &lt;br /&gt;
        Response.Write(&amp;quot;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.ServerVariables(x)); &lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
For Request form&lt;br /&gt;
&lt;br /&gt;
    for(f = new Enumerator(Request.Form()); !f.atEnd(); f.moveNext())&lt;br /&gt;
    { &lt;br /&gt;
      var x = f.item(); &lt;br /&gt;
      Response.Write(&amp;quot;&amp;lt;br&amp;gt;&amp;quot; + x + &amp;quot; = &amp;quot; + Request.Form(x));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Client side DOM - enumerate all checkboxes and set them as checked&lt;br /&gt;
&lt;br /&gt;
  var _cb=document.getElementsByTagName(&amp;quot;input&amp;quot;);&lt;br /&gt;
  for(var i=0;i&amp;lt;_cb.length;i++)&lt;br /&gt;
  {&lt;br /&gt;
    var box=_cb[i];&lt;br /&gt;
	if (box.type==&amp;quot;checkbox&amp;quot;)&lt;br /&gt;
	  box.checked=true;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Useful update from Jeff Richards regarding compressing javascript &lt;br /&gt;
&lt;br /&gt;
http://jscompress.com/&lt;br /&gt;
&lt;br /&gt;
http://javascriptcompressor.com/&lt;br /&gt;
&lt;br /&gt;
Ref: https://community.sagecrm.com/partner_community/b/hints_tips_and_tricks/archive/2013/12/31/sage-crm-7-2-adding-protection-to-your-code-in-script-libraries.aspx&lt;br /&gt;
&lt;br /&gt;
http://devdocs.io/javascript/&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
	<entry>
		<id>https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=241</id>
		<title>General SQL</title>
		<link rel="alternate" type="text/html" href="https://kb.crmtogether.com/index.php?title=General_SQL&amp;diff=241"/>
		<updated>2015-03-01T11:23:30Z</updated>

		<summary type="html">&lt;p&gt;Crmtogetherkb: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Always back up your DB before running any SQL jobs. You run any SQL found on this page at your own risk.&lt;br /&gt;
&lt;br /&gt;
To get the reference id via SQL you run the code as follows:&lt;br /&gt;
&lt;br /&gt;
  Declare @id nvarchar(128) &lt;br /&gt;
  DECLARE @return_value int &lt;br /&gt;
  execute @return_value = [eware_default_values] &#039;Cases&#039;, &#039;Case_CaseId&#039;, &#039;Case_ReferenceId&#039;, 00, @default_value = @id output &lt;br /&gt;
  select id = @id&lt;br /&gt;
&lt;br /&gt;
to run this code in ASP you would have to create the case record using &amp;quot;CreateRecord&amp;quot; and then update the case_referenceid&lt;br /&gt;
&lt;br /&gt;
  var _sp=&#039;Declare @id nvarchar(128) &#039;+&lt;br /&gt;
        &#039;DECLARE @return_value int  &#039;+&lt;br /&gt;
  &#039;execute @return_value = [eware_default_values] \&#039;Cases\&#039;, \&#039;Case_CaseId\&#039;, \&#039;Case_ReferenceId\&#039;, 00, @default_value = @id output  &#039;+&lt;br /&gt;
  &#039;select id = @id &#039;+&lt;br /&gt;
  &#039;update Cases &#039;+&lt;br /&gt;
  &#039;set Case_ReferenceId=@id &#039;+&lt;br /&gt;
  &#039;where Case_CaseId=1&#039;;&lt;br /&gt;
  var rec=CRM.ExecSQL(_sp);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
If you need to re-create a table (say the triggers are corrupted or not running for example) you can do the following.&lt;br /&gt;
&lt;br /&gt;
Copy a table into new table with/without data - SQL Server&lt;br /&gt;
&lt;br /&gt;
Copy only the structure of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld WHERE 1=2&lt;br /&gt;
&lt;br /&gt;
The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).&lt;br /&gt;
&lt;br /&gt;
Copy only the structure with data of an existing table into new table:&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO tblNew FROM tblOld&lt;br /&gt;
&lt;br /&gt;
Ref: http://geekswithblogs.net/nagendraprasad/archive/2009/03/20/copy-a-table-into-new-table-with-and-without-data.aspx&lt;br /&gt;
&lt;br /&gt;
E.G of recreating the phone tables&lt;br /&gt;
&lt;br /&gt;
  SELECT * INTO Phone_new1 FROM phone&lt;br /&gt;
  &lt;br /&gt;
  SELECT * INTO PhoneLink_new1 FROM PhoneLink&lt;br /&gt;
    &lt;br /&gt;
  EXEC sp_rename &#039;Phone&#039;, &#039;Phone_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;Phone_new1&#039;, &#039;Phone&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink&#039;, &#039;PhoneLink_old1&#039;&lt;br /&gt;
  go&lt;br /&gt;
  &lt;br /&gt;
  EXEC sp_rename &#039;PhoneLink_new1&#039;, &#039;PhoneLink&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL code to create a communication notification&lt;br /&gt;
&lt;br /&gt;
NOTE: in CRM 7.2 this code will not be valid as the database structure has changed to have the id columns as identity fields&lt;br /&gt;
&lt;br /&gt;
  Declare @communicationid int &lt;br /&gt;
  EXEC @communicationid=eware_get_identity_id &#039;Communication&#039; &lt;br /&gt;
  INSERT INTO Communication(&lt;br /&gt;
    Comm_CommunicationId,  Comm_Type,  Comm_Action, Comm_Status,                              &lt;br /&gt;
    Comm_Priority, Comm_DateTime,  Comm_Note,  Comm_CreatedBy, Comm_CreatedDate,&lt;br /&gt;
    Comm_UpdatedBy, Comm_UpdatedDate,  Comm_TimeStamp,  Comm_NotifyTime,Comm_Description,&lt;br /&gt;
    Comm_Subject,Comm_SecTerr,comm_taskreminder)&lt;br /&gt;
  VALUES (&lt;br /&gt;
    @communicationid, &#039;Task&#039;,&#039;PhoneOut&#039;,&#039;Pending&#039;,&#039;Normal&#039;,&lt;br /&gt;
    getdate(),&#039;test&#039;,-1,getdate(), -1,getdate(), getdate(),&lt;br /&gt;
    getdate(),&#039;test &#039;,&#039;test&#039;,-2147483640,&#039;Y&#039;&lt;br /&gt;
  )&lt;br /&gt;
  Declare @CmLi_CommLinkId int &lt;br /&gt;
  EXEC @CmLi_CommLinkId=eware_get_identity_id &#039;comm_link&#039; &lt;br /&gt;
  INSERT INTO comm_link(&lt;br /&gt;
    CmLi_CommLinkId,CmLi_Comm_UserId, CmLi_Comm_CommunicationId,CmLi_CreatedBy, CmLi_CreatedDate,&lt;br /&gt;
    CmLi_UpdatedBy, CmLi_UpdatedDate,CmLi_TimeStamp,CmLi_Comm_PersonId, CmLi_Comm_CompanyId,CmLi_Comm_NotifyTime&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    @CmLi_CommLinkId,1,@communicationid,-1,getdate(),-1,getdate(),getdate(),59,45,GETDATE()&lt;br /&gt;
  )&lt;br /&gt;
  Declare @Escl_EscalationId int &lt;br /&gt;
  EXEC @Escl_EscalationId=eware_get_identity_id &#039;Escalations&#039; &lt;br /&gt;
  INSERT INTO Escalations(&lt;br /&gt;
    Escl_TableId,Escl_RecordId,Escl_DateTime,Escl_UserID,Escl_CreatedBy,Escl_CreatedDate,Escl_UpdatedBy,&lt;br /&gt;
    Escl_TimeStamp,Escl_UpdatedDate,Escl_EscalationId&lt;br /&gt;
  )VALUES (&lt;br /&gt;
    29,@CmLi_CommLinkId,getdate(),1,-1,getdate(),-1,getdate(),getdate(),@Escl_EscalationId&lt;br /&gt;
  )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL Trigger on column update. Useful if you need to watch a database column on a 3rd party database and create a notification (as above) in CRM.&lt;br /&gt;
&lt;br /&gt;
  create trigger MyColumnWatcher on dbname.dbo.tablename&lt;br /&gt;
  after update&lt;br /&gt;
  as&lt;br /&gt;
   set NoCount ON&lt;br /&gt;
   if update(table_column_name)&lt;br /&gt;
   begin&lt;br /&gt;
     ---your sql code goes here&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Formating dates in SQL&lt;br /&gt;
&lt;br /&gt;
See &lt;br /&gt;
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:01AM          &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 106) – dd mon yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 108) – hh:mm:ss&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)&lt;br /&gt;
&lt;br /&gt;
                                        – Oct  2 2008 11:02:44:013AM   &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 112) – yyyymmdd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 02 Oct 2008 11:02:07:577     &lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm&lt;br /&gt;
&lt;br /&gt;
                                        – 2008-10-02T10:52:47.513&lt;br /&gt;
&lt;br /&gt;
– SQL create different date styles with t-sql string functions&lt;br /&gt;
&lt;br /&gt;
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd&lt;br /&gt;
&lt;br /&gt;
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm&lt;br /&gt;
&lt;br /&gt;
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Sample code for Bulk import of data into SQL from csv file&lt;br /&gt;
&lt;br /&gt;
  drop table ImportTable&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE ImportTable&lt;br /&gt;
   (reference varchar(20),&lt;br /&gt;
     FullName VARCHAR(100),&lt;br /&gt;
     sortcode VARCHAR(20),&lt;br /&gt;
     accno varchar(20))&lt;br /&gt;
  GO&lt;br /&gt;
&lt;br /&gt;
  BULK INSERT ImportTable&lt;br /&gt;
    FROM &#039;C:\path\Importdata.csv&#039;&lt;br /&gt;
    WITH&lt;br /&gt;
    (&lt;br /&gt;
    FIRSTROW = 2,&lt;br /&gt;
    FIELDTERMINATOR = &#039;||&#039;,  --CSV field delimiter&lt;br /&gt;
    ROWTERMINATOR = &#039;\n&#039;,   --Use to shift the control to next row&lt;br /&gt;
    ERRORFILE = &#039;C:\Marketing\ewt documents\CRMT\DDImportErrorRows.csv&#039;,&lt;br /&gt;
    TABLOCK&lt;br /&gt;
    )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Detecting duplicate rows in SQL&lt;br /&gt;
&lt;br /&gt;
We have seen instances where CRM may have the same phone/email records over and over against the same company. Usually this is due to some import routine going wrong.&lt;br /&gt;
&lt;br /&gt;
Some sample SQL to detect these duplicates is as follows&lt;br /&gt;
&lt;br /&gt;
  select Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number,  Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  from vCompanyPhoneCaption &lt;br /&gt;
  GROUP BY&lt;br /&gt;
      Phon_FullNumber,Phon_AreaCode,Phon_CountryCode,Phon_Number, Plink_Type,plink_recordid,capt_family&lt;br /&gt;
  HAVING&lt;br /&gt;
      COUNT(*) &amp;gt; 1&lt;br /&gt;
&lt;br /&gt;
Next we need to fix the data so we soft delete the phone id&lt;br /&gt;
&lt;br /&gt;
  update Phone&lt;br /&gt;
    set phon_Deleted =1&lt;br /&gt;
     where Phon_PhoneId in ( &lt;br /&gt;
       select Phon_PhoneId&lt;br /&gt;
       from Phone p &lt;br /&gt;
         inner join PhoneLink pl &lt;br /&gt;
         on pl.PLink_PhoneId=p.Phon_PhoneId&lt;br /&gt;
       where &lt;br /&gt;
    Phon_PhoneId not in (&lt;br /&gt;
      select min(Phon_PhoneId) &lt;br /&gt;
      from vCompanyPhoneCaption &lt;br /&gt;
      group by Phon_Number,PLink_Type,plink_recordid,capt_family)&lt;br /&gt;
      and phon_Deleted is null&lt;br /&gt;
      and pl.pLink_EntityID=5)&lt;br /&gt;
&lt;br /&gt;
then we delete the phone link records that are linked to these deleted phone records&lt;br /&gt;
&lt;br /&gt;
  update PhoneLink&lt;br /&gt;
  set PLink_Deleted=1&lt;br /&gt;
  where PLink_PhoneId in (select phon_phoneid from Phone where Phon_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The equivailent for email is&lt;br /&gt;
&lt;br /&gt;
  select Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
    from vCompanyEmailCaption &lt;br /&gt;
    GROUP BY&lt;br /&gt;
      Emai_EmailAddress,Elink_Type,elink_recordid,capt_family&lt;br /&gt;
   HAVING&lt;br /&gt;
     COUNT(*) &amp;gt; 1&lt;br /&gt;
     &lt;br /&gt;
  update Email&lt;br /&gt;
    set emai_Deleted =1&lt;br /&gt;
    where Emai_EmailId in ( &lt;br /&gt;
      select Emai_EmailId&lt;br /&gt;
        from Email e &lt;br /&gt;
        inner join EmailLink el &lt;br /&gt;
        on el.ELink_EmailId=e.Emai_EmailId&lt;br /&gt;
        where &lt;br /&gt;
          Emai_EmailId not in (&lt;br /&gt;
            select min(Emai_EmailId) &lt;br /&gt;
              from vCompanyEmailCaption &lt;br /&gt;
            group by Emai_EmailAddress,Elink_Type,elink_recordid,capt_family)&lt;br /&gt;
    and emai_Deleted is null&lt;br /&gt;
    and el.ELink_EntityID=5)&lt;br /&gt;
   &lt;br /&gt;
  update EmailLink&lt;br /&gt;
    set eLink_Deleted=1&lt;br /&gt;
  where eLink_EmailId in (select emai_emailid from Email where emai_Deleted=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
If you need to reset a tables identity columns here is a sample of sql to do this (applies to any install pre 7.2)&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges &lt;br /&gt;
    SET Range_RangeStart = 200000,&lt;br /&gt;
        Range_RangeEnd = 250000,&lt;br /&gt;
        Range_NextRangeStart = 300001,&lt;br /&gt;
        Range_NextRangeEnd = 350001,&lt;br /&gt;
        Range_Control_NextRange = 400000&lt;br /&gt;
        WHERE Range_TableId =&lt;br /&gt;
                (SELECT Bord_TableId FROM dbo.Custom_Tables &lt;br /&gt;
                        WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
  UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
                WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;tablename&#039;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To generate a new value run the following (*10256 is the table id of the sample table)&lt;br /&gt;
&lt;br /&gt;
        declare @x int&lt;br /&gt;
        exec @x= crm_next_id 10256&lt;br /&gt;
        select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to update the ID value of a table&lt;br /&gt;
&lt;br /&gt;
Fix for this is&lt;br /&gt;
&lt;br /&gt;
  UPDATE dbo.Rep_Ranges&lt;br /&gt;
     SET Range_RangeStart = 200000,&lt;br /&gt;
     Range_RangeEnd = 250000,&lt;br /&gt;
     Range_NextRangeStart = 300001,&lt;br /&gt;
     Range_NextRangeEnd = 350001,&lt;br /&gt;
     Range_Control_NextRange = 400000&lt;br /&gt;
          WHERE Range_TableId =&lt;br /&gt;
     (SELECT Bord_TableId FROM dbo.Custom_Tables&lt;br /&gt;
          WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     UPDATE SQL_Identity SET Id_NextId = 200001&lt;br /&gt;
     WHERE Id_TableId IN (SELECT Bord_TableId FROM dbo.Custom_Tables WHERE bord_name in ( &#039;yourtablename&#039;))&lt;br /&gt;
&lt;br /&gt;
     declare @x int&lt;br /&gt;
     exec @x= crm_next_id 10256&lt;br /&gt;
     select @x&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
update one table based on another&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    Sales_Import&lt;br /&gt;
  SET&lt;br /&gt;
    Sales_Import.AccountNumber = RAN.AccountNumber&lt;br /&gt;
  FROM&lt;br /&gt;
    Sales_Import SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    RetrieveAccountNumber RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.LeadID = RAN.LeadID&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Cross db examples&lt;br /&gt;
&lt;br /&gt;
  UPDATE&lt;br /&gt;
    crmdemo.dbo.company&lt;br /&gt;
  set&lt;br /&gt;
    comp_name = RAN.comp_name&lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..company SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.company  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.comp_companyid = RAN.comp_companyid&lt;br /&gt;
    &lt;br /&gt;
      &lt;br /&gt;
   UPDATE&lt;br /&gt;
    crmdemo.dbo.person&lt;br /&gt;
  set&lt;br /&gt;
    pers_firstname = RAN.pers_firstname ,&lt;br /&gt;
    pers_lastname = RAN.pers_lastname &lt;br /&gt;
  FROM&lt;br /&gt;
    crmdemo..person SI&lt;br /&gt;
  INNER JOIN&lt;br /&gt;
    crm71.dbo.person  RAN&lt;br /&gt;
  ON &lt;br /&gt;
    SI.pers_personid = RAN.pers_personid&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
bcp export&lt;br /&gt;
&lt;br /&gt;
sample code to run from a command line to export data via bcp (bulk copy utility)&lt;br /&gt;
&lt;br /&gt;
bcp &amp;quot;select * from crm.dbo.company&amp;quot; queryout &amp;quot;C:\logs\company.dat&amp;quot; -U sa -P ramdom -c&lt;br /&gt;
&lt;br /&gt;
*if your password contains any odd characters like an ampersand you need to escape them with the ^ character&lt;br /&gt;
&lt;br /&gt;
EG. random^&amp;amp;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Backup/copy a table&lt;br /&gt;
&lt;br /&gt;
To backup or copy a table (structure and contents) you can run something like the following:&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  INTO company_backup&lt;br /&gt;
  FROM company&lt;br /&gt;
&lt;br /&gt;
In this example a table will be created called company_backup with the same structure as company. &lt;br /&gt;
&lt;br /&gt;
This is ideal to test any major data updates on a live system (*always fully backup your live data though)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Remove duplicate row from a table.&lt;br /&gt;
&lt;br /&gt;
The idea here is to create a copy of the table structure you wish to clean up and from there populate with distinct values (removing duplicates)&lt;br /&gt;
&lt;br /&gt;
  EG&lt;br /&gt;
  drop table [CRMEmailPhoneData_new]&lt;br /&gt;
  go&lt;br /&gt;
  CREATE TABLE [dbo].[CRMEmailPhoneData_new](&lt;br /&gt;
	[epd_DataID] [int] not NULL,&lt;br /&gt;
	[epd_EntityID] [int] NOT NULL,&lt;br /&gt;
	[epd_RecordID] [int] NOT NULL,&lt;br /&gt;
	[epd_EmailId] [int] NULL,&lt;br /&gt;
	[epd_EmailAddress] [nvarchar](255) NULL,&lt;br /&gt;
	[epd_PhoneId] [int] NULL,&lt;br /&gt;
	[epd_PhoneCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_PhoneAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_PhoneFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_FaxId] [int] NULL,&lt;br /&gt;
	[epd_FaxCountryCode] [nchar](5) NULL,&lt;br /&gt;
	[epd_FaxAreaCode] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxNumber] [nvarchar](20) NULL,&lt;br /&gt;
	[epd_FaxFullNumber] [nvarchar](47) NULL,&lt;br /&gt;
	[epd_CreatedBy] [int] NULL,&lt;br /&gt;
	[epd_CreatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_UpdatedBy] [int] NULL,&lt;br /&gt;
	[epd_UpdatedDate] [datetime] NULL,&lt;br /&gt;
	[epd_TimeStamp] [datetime] NULL,&lt;br /&gt;
	[epd_Deleted] [int] NULL&lt;br /&gt;
  ) ON [PRIMARY]&lt;br /&gt;
  GO&lt;br /&gt;
  INSERT [CRMEmailPhoneData_new] &lt;br /&gt;
     select distinct ROW_NUMBER() OVER(ORDER BY epd_EntityID DESC) , epd_EntityID, epd_RecordID, epd_EmailId, epd_EmailAddress,&lt;br /&gt;
     epd_PhoneId, epd_PhoneCountryCode, epd_PhoneAreaCode, epd_PhoneNumber,&lt;br /&gt;
     epd_PhoneFullNumber, epd_FaxId, epd_FaxCountryCode,epd_FaxAreaCode,&lt;br /&gt;
     epd_FaxNumber,epd_FaxFullNumber,epd_CreatedBy,epd_CreatedDate,epd_UpdatedBy &lt;br /&gt;
     ,epd_UpdatedDate,epd_TimeStamp,epd_Deleted&lt;br /&gt;
  from [CRMEmailPhoneData]&lt;br /&gt;
  select  *&lt;br /&gt;
  from [CRMEmailPhoneData_new]&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData&#039;, &#039;CRMEmailPhoneData_old&#039;&lt;br /&gt;
  go&lt;br /&gt;
  EXEC sp_rename &#039;CRMEmailPhoneData_new&#039;, &#039;CRMEmailPhoneData&#039;&lt;br /&gt;
  go&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-code to check for duplicate rows&lt;br /&gt;
&lt;br /&gt;
  select epd_EmailAddress, COUNT(epd_EmailAddress)&lt;br /&gt;
  from CRMEmailPhoneData&lt;br /&gt;
  where epd_EmailAddress is not null&lt;br /&gt;
  and epd_EntityID = 13&lt;br /&gt;
  group by epd_EmailAddress&lt;br /&gt;
  having COUNT(epd_EmailAddress)&amp;gt;3&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
The data types text and varchar are incompatible in the equal to operator.&lt;br /&gt;
&lt;br /&gt;
  SELECT *&lt;br /&gt;
  FROM   [Village]&lt;br /&gt;
  WHERE  CONVERT(VARCHAR, CastleType) = &#039;foo&#039;&lt;br /&gt;
&lt;br /&gt;
Ref: http://stackoverflow.com/questions/4350060/where-clause-on-sql-server-text-data-type&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
SQL to detect duplicate Case reference Id values&lt;br /&gt;
&lt;br /&gt;
  select Case_ReferenceId as ref, Case_CreatedDate as cd, Case_CreatedBy as cb, *&lt;br /&gt;
    from Cases &lt;br /&gt;
      where Case_ReferenceId in (&lt;br /&gt;
          select case_referenceid&lt;br /&gt;
             from cases&lt;br /&gt;
           GROUP BY Case_ReferenceId&lt;br /&gt;
            HAVING&lt;br /&gt;
              COUNT(*) &amp;gt; 1)&lt;br /&gt;
     order by Case_CreatedDate desc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
Example: delete all duplicates except one&lt;br /&gt;
&lt;br /&gt;
Here is SQL to set the acc_deleted flag for the duplicates (one copy is left)&lt;br /&gt;
&lt;br /&gt;
It needs to be run more than once or until there are 0 records affected ((0 row(s) affected))&lt;br /&gt;
*Example here is deleting duplicates from CRM account table where there are duplicate acc_companyid&#039;s&lt;br /&gt;
&lt;br /&gt;
  update account&lt;br /&gt;
    set acc_deleted=1&lt;br /&gt;
      WHERE acc_accountid IN(&lt;br /&gt;
       SELECT MAX(acc_accountid)&lt;br /&gt;
       FROM account&lt;br /&gt;
       where acc_deleted is null&lt;br /&gt;
         GROUP BY acc_companyid&lt;br /&gt;
         HAVING COUNT(acc_companyid) &amp;gt;1&lt;br /&gt;
  )and acc_deleted is null&lt;/div&gt;</summary>
		<author><name>Crmtogetherkb</name></author>
	</entry>
</feed>