www.cbizsoft.com - /techsupport/main.htm


I. cBizOne Help/Installation 

  1. Welcome to cBizOne On-Line Help
  2. cBizOne Help PDF
  3. cBizOne PPT1
  4. cBizOne PPT2
  5. cBizOne Installation Document

I.1. Knowledge Block/SoftWare

  1. Exiting way to learn more
  2. Screen recorder software – (Ctrl + Alt + P ---- Pause, Ctrl + Alt + S ----Stop)
  3. Screen recorder software - Used by Sandeep Soni (Camtasia Studio)
  4. Core FTP /Filezilla FTP client Software (Accessing your FTP)
  5. SQL Database Repair Tool - Full Version (or Download from Our Server) and HelpFile
  6. Act Migration
  7. Win RAR
  8. Win RAR 64Bit
  9. Front Page
  10. Vishnu SoftWares
  11. Vishnu [1TestMe] Database for Testing with Insert, Update and Delete Triggers and Original Customization
  12. Vishnu [1DemoDataBase] Database for Testing and Original Customization
  13. Vishnu [1Vishnu_cBiz_test2] Database for Testing
  14. Tracing a website
  15. Video Cache View
  16. cBizOne TSQL Interview Questions1
  17. cBizOne TSQL Interview Questions2
  18. SQL FullText Catalog
  19. UTC DateTime In The Database(Maintain different time zones in single database)
  20. Move Database from One Hosting Server to other (UserID's, Jobs)
  21. Convert Postgre SQL To TSQL Database
  22. Create SQL .csv backup
  23. CLR functions can be much faster for complex string manipulations.

I.1.1. Data Migration

  1. Show all non null columns from the table (CBO_Select_Non_NULL_Columns.sql)
  2. DROP empty Tables and Columns with no Data (CBO_DROP_Empty_Tables_And_Columns_With_No_Data.sql)
  3. Search all tables, all columns for a specific value SQL Server [duplicate] (CBO_Search_All_Tables_Columns_For_Value.sql)
  4. CONVERT all date fields to DATETIME (CBO_CONVERT_All_Date_Fields_To_DATETIME.sql)
  5. Create New Field and Update with value and Delete Existing Field (CBO_Create_New_Field_Update_Delete_Existing_Field.sql)
  6. Generate Real .CSV file for Exelare Import (CBO_Generate_CSV_OutPut.sql)
  7. Get Table and Column Information and Create syntax (CBO_TableColumnInformation_With_CreateTemplate)
  8. Copy data from one table to another table with ID compression (CBO_Copy_Data_From_One_Table_To_Another_Table_With_ID_Compression)
  9. SQLQuery OutPut to a File Document.
  10. Data Migration Script (CBO_ExelareDBMigration1.4.sql)

I.2. PPT Bank

  1. cBiz Tech Questions PDF
  2. cBiz Client Questions PDF
  3. SQL Notes PDF
  4. Analyzing & Optimizing T-SQL Query Performance
  5. Comparation between cBizOne and Exelare record Insertion Order

I.3. Dot Net Application

  1. Vishnu Abstract Paintings

I.3. Web Product (EXELARE)

  1. Exelare Notes
  2. Get up to 3 Links for the Reminder Entry
  3. Exelare DB Check, Set Compatibility and Alter - Version 14.5
  4. For Replicated databases - Download the above Exelare Script (3. Exelare DB Check, Set Compatibility and Alter) and unzip the file and execute "CBO_ExelareDBAlter.sql" on both, Publisher and Scriber database's.
  5. Exelare Script - Upcoming Version
  6. New Modifications Under Customization - Version 1.1
  7. Exelare Dash Report XML Files
  8. Exelare xTab's
  9. Exelare Customize Current View When the Column List Save
  10. Enable Exelare Testing Mode
  11. Exelare Coloring Row
  12. Exelare Report We included CTE, Hidden Col, Used filters on Aliases and Implemented Sub Totals and Grand Total
  13. Create Brand New Database Manually IT/Perm (Script Files)
  14. Create Brand New Database SQLServer2008 Blank_ITConsulting (BackUp)
  15. Create Brand New Database SQLServer2008 Blank_PermStaffing (BackUp)
  16. Copy Items from Consultants to Contacts Vice versa Control throw XML file

I.3.0 Customizations (EXELARE)

  1. Default_Customizations
  2. ITTemplateDB_Customizations
  3. PermTemplateDB_Customizations
  4. ExelereDefaultCustom Released To Srini Not Kris1.2

 I.3.1 EXELARE Functions Etc.

  1. XCBO_SQLMedian
  2. Help Link

I.3.2 EXELARE Reports

  1. cBiz_Medsourcec REPORTS
  2. SLA_Status_Report_Cbiz_CCGI1.1(Bryan)
  3. Metrics Reports 1.5(Bryan)
  4. Sub Reports in Exelare (Custom EntityID, UserGroup Counts, Hide Columns and Jump to SubReports)

I.4. Sarvar Abdullaev (Applications)

  1. Update Candidate from Linked
    1. Extract LinkedIn ID from uuResumeText (SQL Query)
    2. Exelare Linked In Update (.EXE)

II. SQL/SQL Replication

  1. SQL Server 2005 Installation Documentt
  2. SQL Server 2008 Installation Document
  3. SQL Server 2005 - Merge Replication Step by Step Procedure
  4. Merge Replication on Port 4004

II.0 SQL Backup Schedule

  1. Step By Step Scheduling Full Backup, Differential Backup and Restoring differential Backup

II.1 SQL MAIL in SQL SERVER

  1. Database Mail in SQL Server 2005
  2. SQL Mail Summary Counts Report
  3. ERP and ERP Requirement Assignment JOB example
  4. Database Mail Configuration Under SQL 2008 R3

II.2. Customization Folder's

  1. BDT
  2. Consultant
  3. cBizOneIndia Customization and SQL DataBase BackUp
  4. cBizOneUS Customization and SQL DataBase BackUp
  5. SourceFirstIndia
  6. SoftWare

III. UpSize MSAccess database to SQL Server Database

  1. Fix Data - Prepare DB for UpSizing to SQL Server (Start - AllProgrames - cBiz - Fix Data) - Import in to SQL and Run Hosting Script - Chek the FullText Catalog and Schedule Catalog Job (ALTER FULLTEXT CATALOG [CBizOneCatalog] REORGANIZE Exec sp_fulltext_Catalog N'CBizOneCatalog', N'Start_full')
  2. Run the cBiz DSN on client machine and also Check the cBizOne.ini
  3. Run PutResumeInDB.exe - Check is Resumes are updating in Documents Table
  4. Run ExtractFromResume.exe (C:\Program Files\cBiz) - Check in the window DSN Shoud Refelect 

IV. Search

  1. Boolean Search
  2. Searching the Date Time Field

V. App Permissions

  1. cBizOne App Permissions
  2. xBar App Permissions (with Examples)

V.1. HRXML Parser

  1. Parsing Candidate Education Information.

VI. Customize Style Sheet

  1. Customize Style Sheet
  2. Important Information on Style sheets SQL
  3. New Style Sheet (Can pull all tables info)
  4. Tracker Style Sheet (Version 7.3.15)
  5. Sample Soza Style Sheet
  6. Sample Optimal Solutions
  7. XSLT Elements
  8. Edit and Click Me
  9. Help
  10. Help
  11. Help
  12. Consultants xTab to Pull Company Description using Style Sheet

VI.1. cBizOne View's

  1. Interview Call List view in consultants
  2. Indeed, Simple Hired and Glassdoor view's in Consultants
  3. Apply With Indeed view in Consultants

VI.1. More... Button

  1. Enable More... Button
  2. More Button fields Mandatory (Please check the reminders table columns and update if any in the trigger)

VII. Web Posting From cBizOne (.ASP Files)

  1. Post Requirement
  2. Host CProfile form on your website
  3. Adding a New Field in the CProfile
  4. Auto Drop Down Menu
  5. Core FTP Software (Accessing your FTP)

VIII. Web Posting From cBizOne (.ASPX Files)

  1. T-SQL Procedure & Function for WEB-Forms.
  2. Manual For cBizJobs, cProfile, Update cProfile and Update Status. Directly to you database.
  3. Web Form Procedures And Function
  4. cBiz Default Function
  5. Web Form Procedures With Requirement UserID
  6. Core FTP Software (Accessing your FTP)
  7. A Web Based FTP Client
  8. Posting Jobs to Dice.
  9. Placed Status Extra Fields (Client 'Alleanza' Placed CSV)
  10. Nimble Placed

IX.1 T SQL Bank

  1. WITH Common Table Expression (temporary named result sets)
  2. Paging with ROW_NUMBER()

IX.2 Vishnu Testing Bank

  1. Sample_PROCEDURE
  2. Sample_FUNCTION
  3. Sample_GOTO Statement (IMP Use in queries)
  4. Sample_VIEW
  5. Creating Temporary Table
  6. CURSOR Execution Sequence
  7. Sample_CURSOR1
  8. Sample_CURSOR2
  9. Trigger_Note
  10. Sample Insted of Update Trigger
  11. Sample After Update Trigger
  12. Know the Numbet of Triggers on a all Tables
  13. Create Empty Database With Query
  14. UserIDPassD (PDecrypt)
  15. Test cBizOne Login
  16. TSQL Try Catch Block
  17. Know The changes in the Tables
  18. Audit Trigger Using "After Update Trigger" (Not for cBizOne Database as this will not work for NTEXT Field)
  19. Audit cBizOne Insert/Delete Order on the Tables (IMP)
  20. Add date to today but time will be all ways 12:00 AM (US India Date time limit)
  21. Find number of times a string is repeated
  22. Returns the Milliseconds it took to run the QUERY
  23. How to include iFrame
    Example: Client WebSite with cBiz Online WebForms
  24. Color Combos
  25. Instant SQL Formatter
  26. SET NOCOUNT (SET NOCOUNT ON; Impriove Query Performance - We will not get a message like - (1 row(s) affected))
  27. Installing the cBiz Auto Ticketing Bar in Outlook
  28. Ordering the lookup values and Building the New Lookup Values from .txt file
  29. ACLion Audit trial Trigger + xTab(When ever add a column in table, we have to run audit trial trigger one more time)
  30. Excellent Usage of (ROLLBACK TRANSACTION)
  31. FUNCTION to Compare Multi Lookup String Value
  32. FUNCTION and cBiz View for No Activity (consultants EditDate, Activities, History/Notes/Mail, etc) On Consultants Since lats 60 days
  33. Archive candidates with no activity from last 3 years
  34. Transfer candidate’s data from one database to other database including resumes
  35. Copy the consultants.PrimarySkills to Companies.Groups (WITH MULTI LOOKUP) (IMP)
  36. cBiz Lic Count
  37. SQL Query for Summary Report In Months (YEAR1,Data,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nob,DEC) (IMP)
  38. Which gives the top 50 candidates with highest linkeditems
  39. Explicit and Implicit Transaction Demo
  40. Consultants Submitted Status view JOB (Execute in fast)
  41. SQl "NOT IN" Fix for Consultants Submission/Status View (But Kris Say using "dbo.GetReminderLinks()" is good)
  42. Move the lookup group top/bottom
  43. Licenses asp Page Documentation
  44. Create New Link with 3002 Type RQ_CM_3002_1 (exl_phillipsd) (Kris said for Custom Links Create Type from 10000)
  45. Create New Link in Exelare Starting from 10000 (cbiz_test, Exl_JDISearch) (Kris said for Custom Links Create Type from 10000)
  46. Users AppPermissions Update

IX.3. LCA

  1. Sample_LCA_Trigger
  2. IndSoft_LCA_Trigger
  3. Maintain Candidate Company History and show in xTab

IX.4. Client Queries etc

  1. Aclion New Ownership SQL and Doc
  2. Client TNK Delete Document and Make latest Document as Resume

X. Creating New Records in cBiz Database through External application (TSQL Procedures and Functions) and Queries.

  1. Fetching New Record Number for a give Table Name
  2. Creating New Record in cBiz
  3. Creating New Link in cBiz
  4. RECEIVED a Candidate to Requirement
  5. Creating New Link Contact DisplayName and ReqIntID in cBiz
  6. Split Name in to FirstName, LastName and MiddleName.
  7. Submit a Candidate to a Requirement
  8. Creating Status in cBiz
  9. Creating Note in cBiz
  10. Creating New Record Sample for Companies, Contacts, Consultants, Requirements, Links, Status and Note
  11. Creating Note Using Trigger in cBiz
  12. Creating a Appointment/Document/Note/Status Using Trigger in cBizOne (IMP)
  13. Creating a Appointment/Document/Note/Status Using Trigger in cBizOne (IMP with Return Value as NewRecordID)
  14. Creating a Status on Requirement when a field is Updated - Using Trigger in cBizOne (IMP) (Note: Create a Reminder - Note It is safe)
  15. Creating a Note on Contacts when a field is Updated - Using Trigger in cBizOne (IMP Advance) (Note: Recruiters and Sales Goals - ParadigmTechnology)
  16. Creating a Note on Contacts when a field is Updated - Using Trigger in cBizOne (Custom IMP Advance) (Note1: One Field One Status PerDay)
  17. Creating Reminder in cBiz
  18. Creating Reminder in cBiz (New)
  19. Sales Auto Reminder Schedule (Proc's and View)
  20. Creating Reminder in Exelare (Note: Add to Exelare Script file)
  21. Creating Document in cBiz (One Way)
  22. Creating Document in cBiz (Second Way)
  23. Linking a mail to contact
  24. Creating Ticket / Requirement in cBizOne
  25. Link SendMail To cBizOne(Create Record in SenMail)
  26. Import the Excel file with uuMerged=1 and uuID in to cBizOne (Job will run and update the information)(IMP)
  27. Bulk Merge duplicate Candidates on Email1(IMP)(Run Also 'Update Rem Extra Links' From Support App)
  28. Bulk Merge duplicate Candidates on EMail1 and EMail2(IMP)(Run Also 'Update Rem Extra Links' From Support App)
  29. Bulk Merge duplicate Candidates on Phone(IMP)(Run Also 'Update Rem Extra Links' From Support App)
  30. Bulk Merge duplicate Candidates from FromID and ToID(IMP)(Run Also 'Update Rem Extra Links' From Support App)(Kris asked to do for client Time and knowledge)
  31. Bulk Merge duplicate Contacts on Email1(IMP)(Run Also 'Update Rem Extra Links' From Support App)
  32. Bulk Merge Contact With Consultant on Email1 (IMP)(Run Also 'Update Rem Extra Links' From Support App)
  33. INSERT Trigger on Merge duplicate Contacts on Email1(IMP)(Run Also 'Update Reminders Extral Links' From Support App)
  34. BulkMergeDuplicateCandidates for SQL2000(IMP with Limitation)(Run Also 'Update Rem Extra Links' From Support App)
  35. Bulk Merge duplicate Requirements on Field2(IMP it only for Kris (Custom))(Run Also 'Update Reminders Extral Links' From Support App)
  36. Bulk Merge duplicate Candidates on FristName, LastName and (HomePhone, WorkPhone, Mobile) for the client DSN=cbiz_cla(IMP)(Run Also 'Update Rem Extra Links' From Support App)
  37. Bulk Merge duplicate Candidates for Exl_WalkerSearch(This is Custom Don't Run On Other Database)(Run Also 'Update Rem Extra Links' From Support App)
  38. Bulk Merge duplicate Candidates for Exl_Lassen on Duplicate UserField10(This is Custom Don't Run On Other Database)(Run Also 'Update Rem Extra Links' From Support App)
  39. Remove Second Duplicate Record
  40. Shrinking LOG and MDF(IMP)
  41. Delete All the Records Before a Date (Please take the backup of the original database and restore it on new database and run it)(IMP)
  42. DELETE Data and make Brand New Data Base (Please take the backup of the original database and restore it on new database and run it)(IMP)
  43. Make My Database – from the backup database remove all the records other than my records(Not Tested Please Test and Use)
  44. Only Append the QNotes in All the TABLES (There is a BUG, Vishnu know what you want to achive and test it in N directions From Kris Reddy)
  45. Function to format first letter as capital and remaining as lower case when a string is all (Upper/Lower case) (ProperCase a Name)
  46. Function to find UserID in the group type "research" and group name "sourcers"
  47. Function to FindAStatusExist in Submitted/Status
  48. Function and View for ALL History Note Mail Details
  49. Function and View to find HighestStatusID in Submitted/Status
  50. Consultants Highest Submitted/Status cBizOne View(Custom)(RAM)
  51. Auditing the cBizOne Support Tickets
  52. Auditing the Deleted records from table's (Companies, Contacts, Consultants and Requirements)
  53. Auditing the Deleted records from Main table's (Never Delete Trigger's)(IMP)
  54. Auditing the Deleted records from Static View (Never Delete Trigger's)(IMP)
  55. After Trigger - Only particular User can Update a consultant whose Categories is "DNU"
  56. Convert the Resume to Document
  57. Create Document - Input Document(s) from WebForms - on Consultants
  58. Move Private Static View User to Another
  59. Procedure to Return Email ID's of Requirement UserIDs/CoUserIDs.(IMP Usage of SP_ExecuteSQL with OUTPUT parameter)
  60. Checks if particular permission exists to User (Example: 1 For first group and 1 for first group item, 2 for second group and 1 for first group item.)
  61. Update a particular permission to a User(Example: 1 For first group and 1 for first group item, 2 for second group and 1 for first group item.)
  62. Update a particular permission to All User's (Example: 1 For first group and 1 for first group item, 2 for second group and 1 for first group item.)
  63. Update a particular permission to All User's NEW (Example: 0 For first group and 0 for first group item, 1 for second group and 0 for first group item.)
  64. Sample BounceWizard
  65. cBizMergeDBs and CompDBs with Example and Discription
  66. Compare 2 Database's table columns Data with PK ID(v.v.v. Good Code)
  67. List the Most Recent Status Sub Type in the Submitted/Status (TSQL Query)
  68. List the Most Recent Status Sub Type in the Submitted/Status (TSQL Query) IMP
  69. Import Contact CSV in to Companies and Contacts – TSQL query to delete the duplicate Companies and link the marching Contact Company to Company (Use Only for New Database).
  70. Add a missing record from backup database to current database. (Restore deleted record from backup)
  71. Implementing "Teams." under users with uuCoUserIDs field.
  72. Create a Company if a Contact is Drop in static view “Create Company”.
  73. Remove the HTML Tags from the Mail Body.
  74. Update missing Links in MlinkInfo Table from Links Table.
  75. Make India cBizLic to access US database.
  76. Format phone numbers.
  77. No More Multiple Users in Report UserIDs.
  78. GiveMeMyPage - return a requested Page to a sql server.(It will Not Work When Duplicate Columns and Issue with Order By check)
  79. Return the Complete Table's Information (Table Name, Row Count, Column Count and Data Size).
  80. Divide Postal and Zip Code for Consultants.
  81. Converting archived user’s private items to public.
  82. Auditing (Maintaining History) a Field Data by creating a Note
  83. Can Not Update DateTime Under Detail Status
  84. Can Not Update DateTime Under Detail Note
  85. Function to Find is any Company History
  86. Archive Contacts On Email1 With Older EditDate
  87. Return the EmailID of Requirement first UserID
  88. Create a Note when ever a UserID is assigned to requirement (Maintaining when the Recruiter is assigned to a requirement).
  89. SQL Script to create fields in Requirement for "Dice Posting".
  90. Indian City State LookUp".
  91. Med Source/MedSource Client Hierarchy (Company Hierarchy)
  92. Get the total working days in a given two date’s (Excluding ‘Saturday’ and ‘Sunday’)
  93. Pass the Requirement ID, and then it will return the requirements any UserID and Password.
  94. Update the JobType based on JobTitle Using user defined where condition from UserField2 LookUp. (Good Code IMP)
  95. Add Consultants from SQL Server Import/Export Wizard. (IMP)
  96. Update Consultants Field while Submitting a candidate to requirement/Contact.
  97. Detail information of the Users Table (ID, [Type], [Group]).
  98. Can Not Create New Company Record (Read Only - User can not create a new record IMP).
  99. Can Not Create New Consultant/Requirement/Status Record (Read Only - User can not create a new record IMP).
  100. UserIds of a Consultant can be changed only when there is no activity done by the current owner(Consultant.UserIds) for last 30 days.
    User with admin permissions can change the owner(Consultant.UserIds) even before 30 days(IMP)
    .
  101. TSQL function to replace HTML tags with delimiter
  102. Creating User-Defind Table Type (Example)(IMP)
  103. New SQL Format For Exelare (Fast Execution and Complete Control on SQL Query)(IMP)
  104. ENABLE the Triggers even on query Failed (Using Try..Catch Block)(IMP Kris Suggested)
  105. XCBO_SaveUsersPermissions (For Exelare)
  106. cBizOne/Exelare Permissions List(Image)
  107. Convert a Table Rows to Columns(V.V.V.IMP)
  108. Generate Database Schema from Query(IMP)
  109. Update Links If Requirement Contact Is Changed(Ram)
  110. Create New Database with Old Database Schema with Default Data and BackUp Database
  111. Consultants Matched Primary Skills with Requirements Primary Skills - List View
  112. Populate the Reminders Extra Links (Procedure, XCBO_UpdateRemExtraLinks)
  113. Enable/Disable Active Triggers Query (Procedure)
  114. cBizOne Requirements Submitted Status View(Optimized with GetReminderLinks() Table)
  115. Index's Which Improve Submitted Status or PipeLine Query Performance Help Video (With no Table Scan and Optimized to 50% and more)
  116. Update Table SubmittedStatusHistory through Proc and Job Run Proc every 4 Hr Help Video (V.V.V.Optimized Cons Req Submitted Status / PipeLine View with No heavy HDD)
  117. Update Table PipelineHistory through Proc and Job Run Proc every 10 minutes (V.V.V.Optimized Cons Req Submitted Status / PipeLine View with No heavy HDD)(Using SQL MERGE)
  118. Optimized SQL Query From 10 Min to 1 Min (IMP)
  119. Populate PipelineHistory Table Manually (Final Solution for PipelineHistory By Kris)
  120. Populate PipelineHistory Table Manually for custom columns also (Final Solution for PipelineHistory By Kris)
  121. Consultants SubmittedStatus view in PSQL from PipelineHistory Table (PipelineHistory By Kris)
  122. Link Consultants/Contact Company, if already Exist Drop and relink(Company Link)
  123. Maintain SQL JOB History Table (IMP)
  124. Update Consultants From EmpHistory table Latest Record
  125. Allow only Alphabets Numbers and Allowed Special Char
  126. Is Candidate Is Contacts
  127. Change HTML Tag Data in HTML String or Replace data between 2 string
  128. SaveSetInfo Deleted Info BackUp in a Table(Static Views)
  129. Link Candidate to Contact/Requirement

XI. cBizOne Views

  1. Placed Status View Under Requirements
  2. Placed Open, Placed Closed and Placed All Under Requirements
  3. Call/Task List With SubType
  4. Pipeline View Under Consultants/Requirements (Submissions, Highest Status, Received and Potential)
  5. Pipeline View Under Consultants/Requirements (Highest all (Submissions, Status, Received and Potential)) (Bryan Request)
  6. Pipeline View Under Consultants/Requirements (Highest all (Submissions, Status, Received and Potential) linked to all three entities (Consultant, Requirement and Contact)) (Bryan Request)

XI.1 cBizOne X-Tab

  1. XTab with Web Link.
  2. Requirements Description under XTabs.
  3. Custom History/Notes/Mails - XTab with Contact, Candidate details under Requirements.
  4. Received or Potential xTab with Highest Status.
  5. All xTab In Companies, Contacts, Consultants and Requirements

XII. cBizOne Reports

  1. Developing New Reports
  2. Step By Step cBizOne Report Customization (Ram)
  3. View8 Software
  4. Report Submittal Turnaround Time (GOOD)
  5. Complete Requirements Detail and Summary Report
  6. Consultants Potential/Submitted/Status Report
  7. Including the Real number Filter in the Report
  8. Creating a Note on Contacts when a field is Updated - Using Trigger in cBizOne (Custom IMP Advance) (Note1: One Field One Status PerDay. Note2: Recruiters and Sales Goals, with Report - ParadigmTechnology)
  9. Activity Report By Groups (Rasool)

XIII. Basic cBizOne Troubleshooting

  1. Software Limitations
  2. Insert Delete Order in cBizOne
  3. How to Enable the Full Text Catalog
  4. Issue of reflecting the Links table in the cBiz dynamic view
  5. Handling Bugs (Can not Using * and IsNull()) in cBiz.
  6. Default IsNULL() will not work in the cBizOne it will be overwritten by IsNullVBA. So we are creating user defend Function, to handle IsNULL() for String.
  7. Enable the Merge Duplicate Feature for cBizOne Old Customers.
  8. Query Timeout error…
  9. Issue while running Customize wizard(There are three files in the $cBiz\Temp folder. Looks like those files are deleted and hence the issue).
  10. Database in suspect mode- How could I bring it back to normal state? For SQL Server 2000.
  11. How to Convert NVarchar(Max) to Ntext for the working database
  12. Always opening the same record in links window (Reason: Blank Record in Links Table) (Solution: Find and Delete it)
  13. How to Change a Database from One Collation to Other (classic way)
  14. Drop all Constraints, Index and change collation on all the table in a database (Advance Way IMP)
  15. Drop all Constraints and Index on all the table in a database
  16. Get All Indexes List With Involved Columns Name (IMP cool)
  17. Check is all Mandatory Index Exist On a Database (Mandatory Index gave by Kris from DB exl_geckoandrea)
  18. Create Missing Mandatory Index On a Database (Mandatory Index gave by Kris from DB exl_geckoandrea)
  19. Bug Multi Edit Candidates CompanyName Update
  20. Error: Invalid length parameter passed to the substring function.
  21. Complex cBiz View Dump in to a Table and Run the Job as and when required.
  22. Catalog Error (FDHost)
  23. Date Issues in Importing the .mdb in to SQL database
  24. Delete Orphan Records (Since Kris will not delete the documents and Email's)
  25. DELETE Orphan Records from All Main tables (Final, Exclude RecycleBin records)
  26. DELETE The Orphan EMailsSent And Old Emails
  27. Delete the records (Documents and EMailsLinked) from cBizOne before a particular date
  28. Exelare Date Bug (MilliSeconds)
  29. Detecting the SQL Injection (data) on EmailsLinked Table on Column SentFromName
  30. Third Party Hosting (Not setting Private Default value)
  31. Daily Call/Task List Till Current Date In Consultants/Contacts (Date Corrected)
  32. When Kris merge the duplicate candidate, then old resume will add as a document. Then update that document subtype as "Old Resume"
  33. Bug in SQL 2008 it will not convert NVARCHAR(MAX) value '' to NTEXT (Remove '' from NVARCHAR(MAX))
  34. Get business day betwee two dates (Working days: Monday-Friday Holidays: Dec 25, Jan 1, July 4th AND Saturday and Sunday)
  35. Get business day betwee two dates (Client Convergence)
  36. Replace a UserID with another UserID in All Tables (Rasool)

XIV. DashBoard

  1. DashBoard Customizatio Note
  2. Consultants HotList Dashboard
  3. Graphs - LastWeek, ThisWeek and NextWeek
  4. Instead of Interview Status use Interview Schedule in Dashboard
  5. Include Columns in GoogleMashupDash
  6. Chart files
  7. Chart Dashboard for US customization Database
  8. Sample Chart Dashboard
  9. Summary counts Dashboard with click on details
  10. Dashboard to pull Graph data irrespective of Requirements create date (Except Jobs column).

XV. SQL Queries

  1. Audit Trial Trigger for the Tables (Companies, Consultants, Contacts and Requirements)
  2. Audit Trial Trigger for Consultants Notes Only (Consultants)
  3. Audit Trial Trigger for Contacts Notes Only (Contacts)
  4. This will update the static view with contacts that have no activity from past 90 days.
  5. Alphabetic Ordering any Grouped Lookup
  6. Replacing the Lookup Values
  7. Move a Lookup Value
  8. Deleting a Lookup Values
  9. Finding the Duplicate in lookup and Links Table and removing and assign the Primary Keys.
  10. Alter a SQL Server Database as Single User Mode and as Multi User Mode
  11. Get Date from DateTime
  12. Different Date Formats
  13. Number of Duplicate Based on Email1 whose UserField6 = ‘salesforce’ Under Consultants.
  14. It will pull (Report & cBiz View) for all the Contacts that did not have any Activity or (History/Notes/Mails) since last 60 days (This function can be used for both Contacts or Consultants, Jests by passing the appropriate ID) (Below One will be more convenient to client)
  15. Find the Last Activity on Candidates/Contacts Records. (Final Version and Modern with DateTime, ActivityName, UserID)(Works for xBar)
  16. Last Note Mail Activity Tracking on Consultants. (DateTime, ActivityName, UserID)(RAM) (Not works for xBar)
  17. Find the Highest Date from (History/Note/Mail TAB) and Update in Candidates/Contacts Records. (Good only DateTime)(Works for xBar)
  18. Find the Highest ID from (History/Note/Mail TAB) and Update in Candidates/Contacts Records. (Highest HNM IMP, Well Tested)
  19. Function to find the Last Activity DateTime for a Requirement
  20. Updating the latest History event date (History/Notes/Mails) in a Consultants field. (Highest HNM IMP)
  21. Updating the latest History event date (History/Notes/Mails) in Consultants, Contacts and Companies field. (Highest HNM IMP)
  22. Update Consultants/Contact EditDate When (Activity, History/Notes/Mails, Submitted/Status, Received, Potential or Document) added. (IMP)
  23. Return the Number of History Notes Mails
  24. Generating the cBiz Time Stamp by inputing the UserID to the function.
  25. SQL query to DELETE all consultants except the categories with "VAUSA" and also it should DELETE all the history of that consultants.
  26. Basically need a script which creates "SourceFirst" tables for all databases with all constraints etc. If tables already exist it should skip that database..
  27. Create a column AppPermissions under Users table if it is not exist for all Databases.
  28. Copy Consultants, Resumes and Notes form the source database to destination database..
  29. In linking potential candidates to job requirements change find fields to (Company name, contact name, & job title)
  30. This will randomly generates 6 requirement ID's.
  31. IMP Trigger Issue: Update, Insert trigger’s on single TABLE casing issue (Form INSERT trigger calling UPDATE Trigger).
  32. Replace Tab and Space Before After with Nothing for Data Type - Nvarchar Fields.
  33. Calling COM From T-SQL to Implement auto sinking the open jobs from cBizOne to WebSite.
  34. Open / Closed Jobs with FILTERS.
  35. View that shows all the records that have some (at least 5 records) in the Mail/History/Notes folder.
  36. cBiz Views Based on SQL Function.
  37. Highest Status View.
  38. Find Last/Highest Status for a Contact (FUNCTION).
  39. Delete the duplicate Primary ID in Documents which are oldest record based on createdate. (IMP)
  40. Delete the duplicate Consultants based on email ID which are oldest record based on createdate.
  41. DELETE the Duplicate Consultants based on DispalyName and WorkPhone
  42. SQL to Delete the latest duplicates candidates based on (FirstName, MiddleName and LastName) and append the deleted QNotes
  43. Delete the duplicate Consultants based on email ID with less details.
  44. Delete the Duplicate Candidate based on Display name and Phone Numbers. Where resides the record which is having maximum values in the record..
  45. Delete the Duplicate Candidate based on Display name without Phone Numbers and Email1.
  46. Delete duplicate Cunsultants based on emailID which have less details, before deleting copy and append the userID's and Groups.
  47. Delete duplicate Contacts based on emailID which have less details, before deleting copy and append the userID's and Groups.
  48. Delete duplicate Contacts based on emailID which have less details, before deleting copy  and append the userID's.
  49. Not Submitted or Potential to open requirements (View and Function).
  50. Balanced the Counters Values with Tables PrimaryKey.
  51. Trigger to capture the requirement ClosedDateTime Under uuClosedDate.
  52. Received View Under Consultants and Requirements.
  53. Update Highest Note Date into a field under (Companies, Contacts and Candidates).
  54. Update Highest (Note or SentMail or RecMail) Date into a field under (Contacts)*.
  55. Consultant’s Potential view with highest status for a closed requirement.
  56. Delete Duplicate Candidates based on Email1.
  57. Delete all the old Duplicate records from Consultants based on "LastName + CompanyName + WorkPhone".
  58. Delete the OLD duplicates candidates based on UserField10
  59. Delete Duplicate Candidates based on Email1 - for NetPixel Company.
  60. Update the Address info if the Candidate added through Excel Sheet where Import Excel is “True”.
  61. Compare and Update the Fields (Address info, .... ) if the Candidate added through Excel Sheet where uuMatchExcelID is matched to ConsIntID.
  62. Link one more Company to Consultant
  63. Link the Consultants unlinked Company with matching Company in Companies
  64. (Auto Advanced Find...with SQL JOB) Search against "ResumeText" field in the database whose edit date is less than 24 hours. If any results are found we then create a static view and the static view name would be (Company Name + Job Title) and auto Reminder the Requirement UserID.
  65. Search for open Positions and see if they are created for more than 40 days. (This is based on the "CreateDate" field in the database.) then we schedule a reminder in the database for the UserID to whom the position is linked..
  66. Update Consultant ComapanyPhone with Companies CpmpanyPhone (for matching companies)
  67. Trigger to not input duplicate candidates based on displayname and email1 and Make Email1 as compulsory field.
  68. Copy a candidate Tab info to a not when a status (‘Billing Info’) is given to candidate.
  69. Convert all Candidates linked as Potential into Received to a Requirement.
  70. Creating Candidate Profile Link(Trigger).
  71. Ordering Lookup Desc For Non Group LookUps.
  72. Can Not Modify LookUp values.
  73. Drop the column Rowguid from all tables.
  74. Build Manual Submit from Status 'Submit'.
  75. Users Groups.
  76. Re-linking the old status of the requirement to current contact.
  77. Merge City and State for Excel Import on Email1.
  78. Copy the History/Notes/Mail of same contacts from old database to new database.
  79. Received/Potential/Submitted/Status View under Consultants.
  80. Delete Static View Contents Permanently.
  81. Parent Child Relation in Companies Customization.
  82. Capture Server "Date And Time" for Candidate Notes, Status and Potential.
  83. Divide the Contacts in to 10 parts and assign the groups.
  84. Update Archived UserID's with UserID as ',Left,'.
  85. RJT Create a Note to all Candidates and update - Phone info and Email1.
  86. Import Updated Excel sheet from backend and update consultants.
  87. Update Empty Candidate WorkPhone with Company Phone.
  88. Under Requirements xTab, Jump the Consultants from Received to Potential (When Potential) and Potential to Submitted (when Submitted).
  89. Under Requirements xTab, Jump the Consultants from Received to Potential (When Potential) and Potential to Submitted (when Submitted) and also show the Status under that TAB'S.
  90. Jump the candidate from One xTab to another by Status (under requirements)
  91. Delete Static View's for given UserID's.
  92. Delete Static View's for given Single UserID's.
  93. Create a Status by Scheduling the Interview on candidate under requirement Submitted/Status Tab.
  94. Copy Company's Default info to Linked Contacts, if there is no value.
  95. Copy Company Info to Contact while Linking a Company to Contact.
  96. Copy Company Info to Consultants while Linking a Company to Consultants.
  97. Capture the History of a field in Memo Field.
  98. Most Recent Submitted/Status cBizOne View (IMP Optimized with using "With Condiion")
  99. Update Linked Contacts CompanyName (Using RAM Tecknick)
  100. Change Requirement ID to a Number (For RAM)
  101. Create Fields On All Databases on Hosting Server's (IMP)
  102. Get the Space Used and Count of a Single Table on All Database's (IMP)
  103. Shrinking MDF file Demo(On cBiz_Aclion)
  104. ReIndex All Databases (IMP)
  105. cBiz_master Database Script and Job(For New Server SetUp)
  106. Shrink LogFile All HostedDB
  107. Function returns DATEDIFF in HH:MM:SS format
  108. Function returns DATEDIFF in DD:HH:MM format
  109. Function returns DATEDIFF in DD:HH format (Eg: 3 Days, 5 Hours) (Good)
  110. Function returns DATEDIFF in DD:HH:MM format (Client: Convergence)
  111. Function returns string datetime with milliseconds
  112. Remove Control Characters which Are Not Allowed In XML(IMP)
  113. Raise Error Versus Warning mesage from Database in cBizOne/Exelare(CBOWarning and CBOError)
  114. Raise Error Versus Warning mesage from Database in Exelare Demo(CBOWarning and CBOError)
  115. Exelare Users Only can have - Optimizes Submitted/Status, PipeLine and PipeLine Detailed Views(Reminders Extra Links) IMP
  116. Copy Contacts Address To Company Address (If Contact address have more Values)
  117. Find the Maximum Primary Key ID's from the Database for Given SiteID(Exelare Will Not Allow Site as Alphabat)
  118. Extract Number From ZipCode and Rount To 5 Numbers
  119. ZipCodes UK, in a Database(Export to target database)
  120. Calculates the time taken from Requirments.Status = 'Active' To Requirements.Status = 'Filled'(Time To Fill).
  121. Step by Step guide to Deploy SQL Database on SQL AZURE Server.
  122. Convert a non-clustered index on a Primary Key to a clustered index(Sql Azure db Table - Mandatory to have a Clustered Index).
  123. Create Catalog with Consultants, Reminders and Requirements Automatic.
  124. Get the Data Counts in the fields(JobTitle, PrimarySkills, SecondarySkills and OtherSkills)(Srini asked).
  125. Drop All Catalogs, PkIDs, Indexs and Statistics on a Database(Database Without any Schema except Default Values).
  126. Truncate All Tables Except Users and Customizations
  127. Home Tour

XV.0. Important links

  1. http://cbizsoft.com/download/cbizonesp%203.8.34.exe
  2. http://www.cbizsoft.com/download/putresumeindb.exe

XV.1. Kris Data Migration Functions

  1. Remove Duplicate Values from a Field
  2. Remove Special Patten and Build Field LookUp
  3. String To Ascii Char's
  4. Replace Enter(Key) In Text Column's With (BR Tag)
  5. Join Phones and Address to a Main Record from SubTables
  6. Import MySQL DataBase to SQL DataBase
  7. Import MySQL DataBase to SQL DataBase New
  8. Maximizer Tables Massage(AMGR_User_Field_Defs_Tbl and AMGR_User_Fields_Tbl)
  9. Replace Multiple Space With Single Space
  10. Create Tables CS__EduHistory and CS__EmpHistory
  11. Script to Create and Populate data in BullHorn - Table BH_CountryCodes
  12. Import XML file to a Table with Queries for Client (BMQuestorConsultants) - V.V.Good
  13. Compare Difference in two Tables with Data (on Pk ID OR any Column)- V.V.Good (Given to Kris)
  14. Function to check a Valid Email ID
  15. Migrate_data_from_PostgreSQL_to_SQL_Server

1. Find Ntext, Text and Nvarchar(MAX) columns in a Table asdasd

select syscolumns .name as ColumnName
from
sysobjects, syscolumns
where
sysobjects.id =syscolumns. id and sysobjects.xtype ='u' and
(
(
syscolumns .xtype= 231 and syscolumns .length = -1) or -- nvarchar(max)
(
syscolumns .xtype= 99 and syscolumns .length = 16 ) or -- ntext
(
syscolumns .xtype= 35 and syscolumns .length = 16 ) -- text
)
and sysobjects. name = 'Consultants'
order
by sysobjects. name,syscolumns .name

2. Replace Enters key with "<br></br>" for Memo fields while exporting/saving to .CSV

Example:
select REPLACE (REPLACE( REPLACE(CAST (Body AS NVARCHAR(MAX )),char( 13)+ char(10),'<br></br>' ),char( 13), '<br></br>'),char( 10), '<br></br>')
FROM
[1Demodatabase].[dbo] .[EMailsSent]
where
[EMSentIntID] = 'ES00000098'

3. Replace Value from set of mached values(Use of Case)- Maxhire Status denormalized

Example:

SELECT
'WHEN ''' + CAST([CandidStatus_ID] AS NVARCHAR(MAX)) + ''' THEN ''' + [CandidStatusName] +''''
FROM
[MHSEPCMove].[dbo].[CandidStatus]
ORDER BY [CandidStatus_ID]


SELECT
  TOP 100 [uuSourceWebSites],
 
New_Status =
      
CASE [uuSourceWebSites]
           
WHEN '1' THEN 'Monster'
           
WHEN '2' THEN 'Dice'
           
WHEN '3' THEN 'Client'
           
WHEN '4' THEN 'Candidate'
           
WHEN '5' THEN 'Ex-Employee'
           
WHEN '6' THEN 'Employee'
           
WHEN '7' THEN 'LinkedIn'
           
WHEN '8' THEN 'CareerBuilder'
           
WHEN '9' THEN 'Craigslist'
           
WHEN '100000000' THEN 'Monster Job Post'
           
WHEN '100000001' THEN 'Dice Job Post'
           
WHEN '100000002' THEN 'Indeed'
           
WHEN '100000003' THEN 'LinkedIn Job Post'
           
WHEN '100000004' THEN 'Mass Email'
           
ELSE [uuSourceWebSites]
      
END
 
FROM [dbo].[Consultants]
 
WHERE LEN(ISNULL([uuSourceWebSites], '')) > 0

 
UPDATE Consultants SET [uuSourceWebSites]  =
      
CASE [uuSourceWebSites]
           
WHEN '1' THEN 'Monster'
           
WHEN '2' THEN 'Dice'
           
WHEN '3' THEN 'Client'
           
WHEN '4' THEN 'Candidate'
           
WHEN '5' THEN 'Ex-Employee'
           
WHEN '6' THEN 'Employee'
           
WHEN '7' THEN 'LinkedIn'
           
WHEN '8' THEN 'CareerBuilder'
           
WHEN '9' THEN 'Craigslist'
           
WHEN '100000000' THEN 'Monster Job Post'
           
WHEN '100000001' THEN 'Dice Job Post'
           
WHEN '100000002' THEN 'Indeed'
           
WHEN '100000003' THEN 'LinkedIn Job Post'
           
WHEN '100000004' THEN 'Mass Email'
           
ELSE [uuSourceWebSites]
      
END
 
WHERE LEN(ISNULL([uuSourceWebSites], '')) > 0
 

4. Rounding milliseconds in T-SQL

In SQL Server 2008, I have the below column of type DateTime in a table.

SELECT CAST('2009-12-07 10:40:21.893' AS DATETIME2(0)),
      
CAST('2009-12-07 10:42:18.173' AS DATETIME2(0))

5. Rounding or Truncating DateTime to Nearest Day, Hour, Minute or Second

declare @dtVariable as datetime;
set
@dtVariable = getdate();
-- Truncated to the second
select @dtVariable as Original, DATEADD(MILLISECOND, -DATEPART(MILLISECOND, @dtVariable), @dtVariable) as TruncatedToSecond;
-- Rounding to the second

select
@dtVariable as Original, DATEADD(ms, 500 - DATEPART(ms, @dtVariable + '00:00:00.500'), @dtVariable) as RoundedToSecond;
-- Truncated to the minute

select
@dtVariable as Original, DATEADD(minute, DATEDIFF(minute, 0, @dtVariable), 0) as TruncatedToMinute;
-- Rounded to minute

select
@dtVariable as Original,DATEADD(minute, DATEDIFF(minute, 0,DATEADD(second, 30 - DATEPART(second, @dtVariable + '00:00:30.000'),@dtVariable)), 0) as RoundedToMinute;
-- Truncated to the hour

select
@dtVariable as Original,DATEADD(hour, DATEDIFF(hour, 0, @dtVariable), 0) as TruncatedToHour;
-- Rounded to hour

select
@dtVariable as Original,DATEADD(hour, DATEDIFF(hour, 0,DATEADD(minute, 30 - DATEPART(minute, @dtVariable + '00:30:00.000'), @dtVariable)), 0)  as RoundedToHour;
-- Truncated to the day

select
@dtVariable as Original,DATEADD(Day, DATEDIFF(Day, 0, @dtVariable), 0) as TruncatedToDay;
-- Rounded to day

select
@dtVariable as Original,DATEADD(day, DATEDIFF(day, 0,DATEADD(hour, 12 - DATEPART(hour, @dtVariable + '12:00:00.000'), @dtVariable)), 0)  as RoundedToDay;

 

XV.2. SQL Programmability

  1. CBO_IsCBONull
  2. CBO_CHARINDEX2 (Find the Nth Occurrence of a Character in a String)
  3. CBO_DisplayCharactersBeforeAString (In a String Find for a String match and display characters before it)
  4. CBO_Percentage (Find Percentage)
  5. XCBO_ActualWeekMonthYearList (return the list of date limit's in Weeks/Months/Years/Quarterly/Half-Yearly/Yearly)
  6. CBO_LatestStatus (Latest Status on the Consultants) (Final Version and Modern)
  7. CBO_GetEmailSendUserIDsandCounts (From the Email Domain get the EmailSend UserID's and Counts)(Insted of Using Like Operater using the Fulltext Catalog)
  8. CBO_PullNumberFromString (Pull the Starting Number from the String E.g.: ($62k + 25%) 62)

XVI. Error Message

  1. Invalid length parameter passed to the substring function (Download and rand the TSQL query on the client database)

XVII. Other

  1. Procedure to enable the Custom Parser with Example
  2. Boolean Parser
  3. Resume Preparation
  4. Coloring The Fields In cBizOne
  5. DashBoard with Filters
  6. Chat (Update the Text File and Read it)
  7. Snagit SoftWare
  8. VB Script Functions
  9. How to Improve Your Website's Google Ranking
  10. Mails Not Sent By Support Team (Employee Leave calculation)

XVII.1 Other

  1. Invite People For Vipassana Meditation

XVIII. Srini Query & Other

1. We can RUN the below Queries on SQL Server "sql3.network80.com" and Database "cBizSoft"

SELECT *
FROM dbo.AllHostedDB
ORDER BY SQLServerName
 
SELECT *
FROM dbo.ContactsInfoOnServerName('sql3.network80.com,sql.network80.com')
ORDER BY SQLServerName
 
SELECT *
FROM dbo.HostedDBNotInLogins
ORDER BY SQLServerName

SELECT *
FROM dbo.HostedDBNotInLiveButInLogins
ORDER BYLoginsSQLServer

XVIII.1. Functions, Procedures and Jobs On (License Database cBizSoft)

  1. Function_ContactsInfoOnServerName
  2. Function_CBO_USA_LicAddPending_Detail
  3. Function_CBO_USA_LicAddedCancel_Gained_Count
  4. Function_CBO_USA_LicAddedCancel_Detail
  5. Function_CBO_USA_LicAddedCancel_Count_Detail
  6. Function_CBO_USA_LicAddedCancel_Count
  7. Function_CBO_Return_Dates_From_DateValue
  8. Function_CBO_LicenseCountWithDateRange
  9. Function_CBO_Convert_Rows_INTO_Columns
  10. Function_CBO_TillNowNoOfYearsMonthsDays
  11. Function_CBO_IsCountZero
  12. Function_CBO_GetCompanyNameForBID
  13. Function_CBO_DisplayCharactersBeforeAString
  14. Function_CBO_Number_Search_Check
  15. Procedure_Vishnu_Recordnumber
  16. Procedure_RemoveCBO_LicenseCountDataForChart
  17. Procedure_CBO_LogIns_Vishnu_App
  18. Procedure_CBO_LicenseStatus_UPDATE
  19. Procedure_CBO_IsUserAdmin_Vishnu_App
  20. Procedure_CBO_EvalClients_xUsers_Vishnu_App
  21. Procedure_CBO_JOB_Vishnu_Update_Table_Job_Queries
  22. Procedure_CBO_Procedure_ActiveLicenseDetail
  23. View_HostedDBNotInLogins
  24. View_HostedDBNotInLiveButInLogins
  25. View_CBO_TodaysLicenseCount
  26. View_CBO_Last30MinLicenseCount
  27. View_CBO_ActiveLicenseCompanyDomain
  28. View_cBizExl
  29. View_AllHostedLogins
  30. View_AllHostedDB
  31. View_CBO_Vishnu_ActiveLicenseDetail
  32. Job_cBizSoft_TodaysLicenseCount
  33. Job_cBizSoft_Last30MinLicenseCount
  34. Job_cBizSoft_TicketingDBEmailCount
  35. cBizClients View (This View is used by cBizClients.exe) (Select Query is Optimized using Having Clause)
  36. Linked Servers and SQL Jobs

XVIII.2. Functions, Procedures and Jobs On (Ticketing Database cBizSoft)

  1. Function_CBO_TotalOpenTickets
  2. Function_CBO_GetEmailSendUserIDsandCounts
  3. Function_CBO_cBizTimeStamp
  4. Procedure_CBO_JOB_Ticketing_EmailInfo_VishnuApp
  5. Procedure_CBO_CreateTicket
  6. Procedure_CBO_ClearOpenMarketingTic
  7. View_CBO_LicCountSummary
  8. View_CBO_cBizOneTicketingDBEmailDomainCount
  9. View_CBO_cBizOneTicketingDBEmailCountMAIN
  10. View_CBO_cBizOneTicketingDBEmailCount
  11. Job_CBO_JOB_Ticketing_EmailInfo_VishnuApp
  12. Linked Servers and SQL Jobs

XIX.0 T-SQL Query & Database Optimization

1. Autogrowth of Database Should be minimum 64MD

All DataBase:

SELECT 'USE [master]
GO
'

UNION
ALL
SELECT
'ALTER DATABASE ['+DatabaseName+'] MODIFY FILE ( NAME = N'''+LogicalFileName+''', FILEGROWTH = 65536KB )
GO
'

FROM

(
SELECT DB_NAME(s_mf.database_id) AS DatabaseName, name AS LogicalFileName, (CONVERT(BIGINT, growth) * 8) AS FILEGROWTH
FROM
sys.master_files s_mf
WHERE
s_mf.state = 0 -- ONLINE
AND
has_dbaccess(db_name(s_mf.database_id)) = 1 AND db_name(s_mf.database_id) NOT IN ('master', 'tempdb', 'model', 'msdb')
AND
db_name(s_mf.database_id) NOT LIKE 'ReportServer%' AND type = 0 AND is_percent_growth = 0
)
TEMP
WHERE
FILEGROWTH < 65536

Single Database:
ALTER DATABASE [DatabaseName] MODIFY FILE ( NAME = N'DatabaseName', FILEGROWTH = 65536KB )
GO
 

2. Correct SQL TDS packets size, will Improve the Query Performance.

You can configure the SQL Server packet size, which is the size of the TDS packets. The size of the TDS packets defaults to 4 KB on most clients (DB-Library applications default to 512 bytes), which testing has shown to be the optimal TDS packet size in almost all scenarios.

3. Using with (nolock) and with (readpast).

SELECT *
FROM
[dbo].[Consultants] with (nolock)

SELECT
*
FROM
[dbo].[Consultants] with (readpast)

It is recommended to use NOLOCK in joins. which is a major performance and scalability improvement.

SQL Server NOLOCK Hint:
The NOLOCK and READUNCOMMITTED table hints are equivalent. When these table hints are used, dirty reads are allowed. It means that current transaction does not issue shared locks and other transactions are able to modify the data which is being read by the current transaction. Also, exclusive locks do not block the current transaction enabling it to read locked data. As a result, we can read uncommitted data.

SQL Server READPAST Table Hint:
When the SQL Server READPAST table hint is used, the database engine does not read rows locked by other transactions. Unlike the NOLOCK table hint, READPAST does not allow dirty reads (according the definition - Dirty Reads occur when transaction reads modified but not yet committed data by other transactions). However, when using the READPAST hint reading incorrect data is also possible, because locked rows are skipped, so we can miss some data which meet our criteria.

Conclusion:
Generally reading any uncommitted data or missing some data during a SELECT statement can cause problems, however Microsoft SQL Server allows this kind of reads by using the NOLOCK (or using READUNCOMMITTED transaction isolation level) and READPAST table hints. These hints should be used carefully and the developer should understand their meaning and behavior to avoid mistakes in the application.

This will help in under Large Database with more Licenses.

4. Index, File Grouping, TempDB, Statistics Etc...

Document: TSQL_IMP_Topics_Help_Doc

5. Hosted Server Maintenance Plans.

Document: TSQL_IMP_Topics_Help_Doc

Index Rebuild : This process drops the existing Index and Recreates the index.
USE AdventureWorks;
GO
ALTER INDEX ALL ON Production.Product REBUILD
GO

Index Reorganize : This process physically reorganizes the leaf nodes of the index.
USE AdventureWorks;
GO
ALTER INDEX ALL ON Production.Product REORGANIZE
GO

Recommendation: Index should be rebuild when index fragmentation is great than 40%.

6. Temp Tables vs Table Variables vs Memory Optimized Table Variables.

Note: Temp tables and Table variables are not real memory variables, they store in the Tempdb.
          We have a new Concept in SQL 2014 Memory Optimized Table Variable, this variablea are not created in Tempdb,
          instead created in the Memory hence they are 10 times faster that regular tables.

ALTER DATABASE [1Demodatabase] ADD FILEGROUP [ImaNewFileGroup] CONTAINS MEMORY_OPTIMIZED_DATA
GO
ALTER
DATABASE [1Demodatabase] ADD FILE (name='imanewfilegroup_1', filename='D:\Main\SQL\DataBase\imanewfilegroup_1')
TO
FILEGROUP [ImaNewFileGroup];
GO
ALTER
DATABASE [1Demodatabase] SET MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT ON;
GO

CREATE
TYPE TM1 as TABLE (
  
IDx INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  
Data NVARCHAR(512)

)
WITH (MEMORY_OPTIMIZED = ON)
GO

CREATE TABLE MEMORY_OPTIMIZED_Table1(
IDx INT  IDENTITY(1,1) PRIMARY KEY NONCLUSTERED,
Data NVARCHAR(512)

)
WITH (MEMORY_OPTIMIZED = ON)
GO


Summary on In-Memory OLTP Table
1. The entire table resides in memory and also on HDD
2. It will not Support 'text' datatype
3. The maximum row length of a memory-optimized table is limited to 8060 bytes.
4. We can not add/remove/alter columns
5. Triggers not supported
6. Best use of In-Memory OLTP Table achieved through "Natively-compiled stored procedures" not from queries.

Above limitations will not allow us to use for our application.

Help Linkkk

7. Include columns in index.

An index is typically

CREATE INDEX <name> ON <table> (KeyColList) INCLUDE (NonKeyColList)

Where:
KeyColList = Key columns = used for row restriction and processing
WHERE, JOIN, ORDER BY, GROUP BY etc

NonKeyColList = Non-key columns = used in SELECT and aggregation (e.g. SUM(col)) after selection/restriction

8. Indexed View / HDD Stored Views(Table).

Document: Indexed_View_Help_Doc

9. Check Query Performance and it's Query Plan.

SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
qs.execution_count AS [Execution Count],

CAST
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
t.text

,
NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?')
,
NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?')
,
NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?')
,
NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?')
,
NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
,
'&','&amp;'),'>','&gt;'),'<','&lt;') AS XML) AS [Query Text],
CAST
((qs.total_worker_time/1000000.0) AS DECIMAL(16,1)) AS [Total Worker Time in Sec],
qs.max_worker_time AS [Max Worker Time],
qs.total_worker_time AS [Total Worker Time],
qs.max_logical_reads AS [Max Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.max_elapsed_time AS [Max Elapsed Time],
qs.creation_time AS [Creation Time],
qp.query_plan AS [Query Plan]

FROM
sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS
APPLY sys.dm_exec_sql_text(plan_handle) AS t
CROSS
APPLY sys.dm_exec_query_plan(plan_handle) AS qp
WHERE
CAST(query_plan AS NVARCHAR(MAX)) LIKE ('%CONVERT_IMPLICIT%')
 --AND t.[dbid] = DB_ID()

ORDER
BY qs.total_worker_time DESC OPTION (RECOMPILE);

10. Activity Monitor in SQL Server Management Studio.

Open Activity Monitor at any time by pressing CTRL+ALT A.

XIX. T-SQL Query & Other

1. How to determine which version, SQL Bit and More... of SQL Server (Service pack):

SELECT SERVERPROPERTY('Edition')
EXEC master
.dbo.xp_msver

SELECT
@@version
SELECT
SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition') 

1.1. Attention Using SET QUOTED_IDENTIFIER OFF (Use Both Off and On Or else it will effect the Procedure):

SET QUOTED_IDENTIFIER OFF
... Procedure/Function...
SET
QUOTED_IDENTIFIER ON

SELECT SCHEMA_NAME(s.schema_id)  + '.' + s.name AS name,s.create_date,s.modify_date,
   
OBJECTPROPERTY(s.object_id,'ExecIsQuotedIdentOn') AS IsQuotedIdentOn

FROM
sys.objects s 
WHERE
s.type IN ('P','TR','V','IF','FN','TF')
   
AND OBJECTPROPERTY(s.object_id,'ExecIsQuotedIdentOn') = 0

ORDER
BY SCHEMA_NAME(s.schema_id)  + '.' + s.name DESC   

1.2. How to check if a function exists on a SQL database:

IF EXISTS (SELECT * FROM   sys.objects
          
WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                 
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
 

2.1. Re-Indexing one Table Column:

DBCC DBREINDEX ("Companies", aaaaaCompanies_PK,80)

2.2. Re-Indexing all the main Tables:

DBCC DBREINDEX ('Companies' , ' ', 80)
DBCC
DBREINDEX ('Consultants' , ' ', 80)
DBCC
DBREINDEX ('Contacts' , ' ', 80)
DBCC
DBREINDEX ('Documents' , ' ', 80)
DBCC
DBREINDEX ('EMailsLinked' , ' ', 80)
DBCC
DBREINDEX ('EMailsSent' , ' ', 80)
DBCC
DBREINDEX ('Links' , ' ', 80)
DBCC
DBREINDEX ('Lookup' , ' ', 80)
DBCC
DBREINDEX ('MLinkInfo' , ' ', 80)
DBCC
DBREINDEX ('Reminders' , ' ', 80)
DBCC
DBREINDEX ('Requirements' , ' ', 80)
DBCC
DBREINDEX ('SaveSetInfo' , ' ', 80)
DBCC
DBREINDEX ('SaveSets' , ' ', 80)

Procedure

2.3. Create Index On a Column:

CREATE INDEX [UserField10] ON [Consultants]([UserField10]) ON [PRIMARY]

3. How to register Dll and Exe in command-line:

To un/register Dll:
c:\>regsvr32 "C:\Windows\System32\My.dll"
c:\>regsvr32 /u "C:\Windows\System32\My.dll"

To un/register Exe:
c:\>"C:\Program Files\MyAppLocation\My.exe" /REGSERVER
c:\>"C:\Program Files\MyAppLocation\My.exe" /UNREGSERVER

4. Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition:

SELECT ReqIntID, ROW_NUMBER() OVER (ORDER BY ReqIntID ) AS 'RowNumber'

FROM Requirements

5. Shrink Log File Script :

BACKUP LOG cBizOne WITH TRUNCATE_ONLY

DBCC Shrinkfile ('cBizOne_log',2)

For SQL SERVER 2008:

USE AdventureWorks;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks
SET RECOVERY SIMPLE;
GO

6. How to Change The Logical File Names of SQL Server Databases:

You can not change the database file name using the GUI (Graphical User Interface) of the SQL Management Studio in SQL 2005 or the Enterprise Manager in SQL 2000.
But you can use the ALTER DATABASE sql command as shown below :

ALTER DATABASEProduct

MODIFY FILE (NAME = ProductTest_Data, NEWNAME = Product_Data)

This command returns the below message if it is successfull
The file name 'Product_Data' has been set.

ALTER DATABASEProduct

MODIFY FILE (NAME = ProductTest_Log, NEWNAME = Product_Log)

This command returns the below message if it is successfull
The file name 'Product_Log' has been set.

7. How to SRINIK SQL Server Databases: The file size will not decrease when you delete data. In order to decrease the file size, you must run DBCC SHRINKFILE.

exec sp_spaceused

USE VishnuTest1

DBCC SHRINKFILE ('VishnuTest1')

GO

DBCC SHRINKFILE ('VishnuTest1_log')

GO

8. How to copy data from one table to other table:

INSERT INTO cBizOne_ProductMarketing. DBO.CONTACTS

SELECT *

FROM cBizOneIndia.DBO.CONTACTS

WHERE (COMPANYNAME LIKE 'CBIZ%') AND
(COUNTRY LIKE 'US%') AND
(CONTACTINTID!='CNZ0001169')

9. Executes a Transact-SQL statement:

EXECUTE sp_executesql N'SELECT * FROM AdventureWorks.HumanResources.Employee
WHERE ManagerID = @level'
,
N
'@level tinyint',
@level
= 109 ;

10 ALTER TABLE and Add Column and Constraint:

--Kris said to use this
ALTER
TABLE SaveSetInfo ADD SaveSetType nvarchar(20) NOT NULL DEFAULT ''
ALTER
TABLE SaveSetInfo ALTER COLUMN SaveSetType nvarchar(20) NULL 

OR

ALTER TABLE Requirements ADD
uuRunJob BIT NOT NULLDEFAULT (0)

10.1 Delete column with Constraint and ALTER Column name:

DECLARE @SQL_Text NVARCHAR(MAX) = ''
IF
((SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Requirements' AND (COLUMN_NAME = 'ClientRate' OR COLUMN_NAME = 'ClientRate_OLD_DB')) = 2)
IF
(((SELECT COUNT(1) FROM Requirements WHERE ISNULL(ClientRate,0.00) != 0.00) = 0) AND ((SELECT COUNT(1) FROM Requirements WHERE LEN(ISNULL(ClientRate_OLD_DB,'')) > 0) > 0))BEGIN
      
SELECT @SQL_Text += '

      
ALTER TABLE '
+ t.name + ' DROP CONSTRAINT ' + df.name + '
      
ALTER TABLE '
+ t.name + ' DROP COLUMN ' + c.NAME + '
      
EXEC sp_rename ''Requirements.ClientRate_OLD_DB'', ''ClientRate'', ''COLUMN'';'

      
FROM sys.default_constraints df
      
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
      
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
      
WHERE t.name = 'Requirements' AND c.NAME = 'ClientRate'

END
IF
((SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Consultants' AND (COLUMN_NAME = 'Rate' OR COLUMN_NAME = 'Rate_OLD_DB')) = 2)
IF
(((SELECT COUNT(1) FROM Consultants WHERE ISNULL(Rate,0.00) != 0.00) = 0) AND ((SELECT COUNT(1) FROM Consultants WHERE LEN(ISNULL(Rate_OLD_DB,'')) > 0) > 0))
BEGIN

      
SELECT @SQL_Text += '

      
ALTER TABLE '
+ t.name + ' DROP CONSTRAINT ' + df.name + '
      
ALTER TABLE '
+ t.name + ' DROP COLUMN ' + c.NAME + '
      
EXEC sp_rename ''Consultants.Rate_OLD_DB'', ''Rate'', ''COLUMN'';'

      
FROM sys.default_constraints df
      
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
      
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
      
WHERE t.name = 'Consultants' AND c.NAME = 'Rate'

END
IF
(LEN(@SQL_Text) > 0)
BEGIN

 
--PRINT @SQL_Text
 
EXECUTE(@SQL_Text)
 
PRINT 'Done.'

END
 

11. Changing the field size:

ALTERR TABLE Consultants
ALTER
COLUMN UserField5 NVARCHAR (200) NULL

ALTER TABLE EMailsSent ADD
UUBody1 NTEXT NULL

11.1. Change field DataType:

DECLARE @Requirements_Rate_Constraint NVARCHAR(100), @SQLQuery NVARCHAR(MAX)

SELECT
@Requirements_Rate_Constraint = OBJECT_NAME(O.OBJECT_ID)
FROM
sys.objects O, sys.columns C
WHERE
(O.parent_object_id = C.object_id) AND OBJECT_NAME(O.parent_object_id) = 'Requirements' AND O.type_desc LIKE '%CONSTRAINT'
AND
(C.default_object_id = O.object_id) AND (C.name = 'Rate')

SELECT
@SQLQuery = '
ALTER  TABLE [dbo].Requirements DROP CONSTRAINT '
+ @Requirements_Rate_Constraint + '
ALTER  TABLE [dbo].Requirements ALTER COLUMN Rate NVARCHAR(80) NULL
ALTER  TABLE [dbo].Requirements ADD CONSTRAINT '
+ @Requirements_Rate_Constraint + ' DEFAULT ('''') FOR Rate'

EXEC
(@SQLQuery)

=====
DECLARE @EMailsLinked_Info_Constraint NVARCHAR(128), @SQLQuery NVARCHAR(MAX) 
SELECT
@EMailsLinked_Info_Constraint = OBJECT_NAME(O.OBJECT_ID)
FROM
  sys.objects O, sys.columns C
WHERE
(O.parent_object_id = C.object_id) AND  OBJECT_NAME(O.parent_object_id) =  'EMailsLinked' AND O.type_desc LIKE '%CONSTRAINT'
AND
(C.default_object_id = O.object_id) AND (C.name = 'Info')

SELECT
@SQLQuery = '
ALTER  TABLE [dbo].EMailsLinked DROP CONSTRAINT ' + @EMailsLinked_Info_Constraint  + '
ALTER  TABLE [dbo].EMailsLinked ALTER COLUMN Info VARCHAR(max) NULL
ALTER  TABLE [dbo].EMailsLinked ADD CONSTRAINT '
+ @EMailsLinked_Info_Constraint  + ' DEFAULT ('''') FOR Info'

EXEC
(@SQLQuery)

Note: Which completes the conversion by moving the data from the lob structure to the table (if the length in less than 8k), which improves performance / keeps things proper.

UPDATE
[dbo].EMailsLinked SET Info = Info
WHERE
1 = 1

11.2. Get Column Constraint Name:

SELECT OBJECT_NAME(O.OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME
(O.schema_id) AS SchemaName,
OBJECT_NAME
(O.parent_object_id) AS TableName,
O.type_desc AS ConstraintType, C.name as ColumnName

FROM
sys.objects O, sys.columns C
WHERE
(O.parent_object_id = C.object_id) AND OBJECT_NAME(O.parent_object_id) = 'Requirements' AND O.type_desc LIKE '%CONSTRAINT'
AND
(C.default_object_id = O.object_id) AND (C.name = 'Rate')

12. Calculate Percentage Under Reports (VB Script):

If RTPeople = 0 Then If RTPeople = 0 Then
Persent.Value = 0
Else
Persent.Value = FormatPercent(RTLast30Days/RTPeople,0)
End If

IF (LEN(txtUserID10)>0) THEN
Line13.Visible=True
txtUserID10.Visible=True
txtTotal.Left=txtTotal.Left+895
Line.Width=Line.Width+895

IF ((StrComp(Theme,"Table Style 2")=0) or (StrComp(Theme,"Table Style 3")=0) or (StrComp(Theme,"Table Style 4")=0)) THEN
Line.Visible=False
END IF
END IF IF (StrComp(Theme,"Table Style 1")=0) THEN
RTCTotal="ffffff"

txtTotal1.ForeColor = "&H000000"
txtUserID1.ForeColor = "&H000000"
txtUserID2.ForeColor = "&H000000"
txtUserID3.ForeColor = "&H000000"
txtUserID4.ForeColor = "&H000000"
txtUserID5.ForeColor = "&H000000"
txtUserID6.ForeColor = "&H000000"
txtUserID7.ForeColor = "&H000000"
txtUserID8.ForeColor = "&H000000"
txtUserID9.ForeColor = "&H000000"
txtUserID10.ForeColor = "&H000000"
txtTotal.ForeColor = "&H000000"
END

<Name>txt1</Name>
<Section>0</Section>
<Text>PeakRank</Text>
<Calculated>-1</Calculated>
<Left>30</Left>
<Top>30</Top>
<Width>1345</Width>
<Height>270</Height>
<Align>7</Align>
<WordWrap>0</WordWrap>
<Font> <Name>Tahoma</Name>
<Size>8.25</Size>
<Bold>-1</Bold>
</Font>
</Field>

12.1. Remove the Default date Under Reports (VB Script):

If DateValue(SubmittedDate) = DateValue("1/1/1900") Then
Consultant1.Value = ""
End If

12.2.How to make SQL single User:

ALTER DATABASE [DatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

ALTER DATABASE [DatabaseName] SET SINGLE_USER
GO

Use Master
GO

ALTER DATABASE Database Name SET MULTI_USER
GO

12.3. How to Kill the "session ID" It is used to convert database from multiuser to single user

SELECT SPID FROM master.. sysprocesses
where
dbid =db_id ('DemoDataBase' ) and spid <> @@spid

KILL 69

AND

use master
SELECT
request_session_id
FROM
   sys.dm_tran_locks
WHERE
  resource_database_id = DB_ID('cbiz_vgroup')

kill 295 

Set Database to Multi_User/Single_User
ALTER
DATABASE [Works] SET MULTI_USER WITH NO_WAIT
ALTER
DATABASE [Works] SET SINGLE_USER WITH NO_WAIT

USE [master];
ECLARE
@kill varchar(8000) = ''; 
SELECT
@kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';' 
FROM
sys.dm_exec_sessions
WHERE
database_id  = db_id('Exelare2019')

EXEC
(@kill);

ALTER
DATABASE [Exelare2019] SET MULTI_USER WITH NO_WAIT  

12.4. The database principal owns a schema in the database, and cannot be dropped

SELECT name FROM  sys.schemas WHERE principal_id = USER_ID('1Demodatabase')

ALTER
AUTHORIZATION ON SCHEMA::SchemaName TO dbo
GO
DROP
USER myUser

13.Repaire SQL Database:

dbcc checkdb('cBizOne',Repair_rebuild)

13.1 Repaire SQL Database with Data Loss:

USE Exl_VishnuTest1XYZ

ALTER
DATABASE Exl_VishnuTest1XYZ SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
BEGIN
TRAN T1;
DBCC
CHECKDB ('Exl_VishnuTest1XYZ', REPAIR_ALLOW_DATA_LOSS);
COMMIT
TRAN T1; 
ALTER
DATABASE Exl_VishnuTest1XYZ SET MULTI_USER; 

13.2 Client complaints on Exelare TimeOut:

ALTER DATABASE [Exl_eProCorp] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
BEGIN
TRAN T1;
DBCC
CHECKDB ('Exl_eProCorp', Repair_rebuild);
COMMIT
TRAN T1; 
ALTER
DATABASE [Exl_eProCorp] SET MULTI_USER;

Srini Ran following Successfully.
1. DBCC CHECKDB - All Good
2. Shrinked .MDF - Done
3. ReIndexing - Done
4. Catalog Drop and Recreated - Done
5. Incresed the AutoFileGrouth to 64MB - Done

14. CATALOG Script (SQL 2005):

Start Optimize Catalog Population on cbiz_Ashton.CBizOneCatalog

cbiz_Ashton Full text indexing

ALTER FULLTEXT CATALOG [CBizOneCatalog] REORGANIZE
exec sp_fulltext_catalog N'CBizOneCatalog', N'start_full'

14.1. Delete a full-text catalog from a Table

DROP FULLTEXT INDEX ON [dbo].[Consultants]
GO

15. DATALENGTH() This function can be used on all data types (Text, Ntext, Image) in your table.

16.  Blanking the Admin password:

UPDATE Users SET Password= '' WHERE ID='Admin' AND RecType= '20'

17. Set the default admin permissions

UPDATE Users SET Field1 = '2047,963,963,963,963,963,963,963'
WHERE
(RecType = '20') AND (ID = 'Admin') AND
(
RPointer = '0,0') AND
(IsAdmin = 1)

18. Split path and file name

SELECT 'C:\Users\aiacullo\Documents\Resumes\Comp Analyst-Acctg\Figueroa, Rebecca.doc'

SELECT REVERSE(SUBSTRING(REVERSE('C:\Users\aiacullo\Documents\Resumes\Comp Analyst-Acctg\Figueroa, Rebecca.doc'),PATINDEX('%\%',REVERSE('C:\Users\aiacullo\Documents\Resumes\Comp Analyst-Acctg\Figueroa, Rebecca.doc')),1000))

SELECT REVERSE(SUBSTRING(REVERSE('C:\Users\aiacullo\Documents\Resumes\Comp Analyst-Acctg\Figueroa, Rebecca.doc'),0,PATINDEX('%\%',REVERSE('C:\Users\aiacullo\Documents\Resumes\Comp Analyst-Acctg\Figueroa, Rebecca.doc'))))

Example:

UPDATE Consultants

SET ResumeDir = REVERSE(SUBSTRING(REVERSE(ResumeFile),PATINDEX('%\%',REVERSE(ResumeFile)),1000)),

ResumeFile = REVERSE(SUBSTRING(REVERSE(ResumeFile),0,PATINDEX('%\%',REVERSE(ResumeFile))))

WHERE (ResumeFile like '%:%')

Example1: Remove incomplet data =  SELECT SUBSTRING('Cromwell, Arletta, E',1,LEN('Cromwell, Arletta, E') - PATINDEX('%,%',REVERSE('Cromwell, Arletta, E'))) = O/P Cromwell, Arletta

19.1 Adding columns in 2000 replication database

sp_repladdcolumn @source_object = 'Users'

, @column = 'AppPermissions'

, @typetext = 'ntext NULL'

, @publication_to_add = 'cBiz_rjt'

19.2 Adding/Deleting the columns in 2005 replication database

sp_repladdcolumn [ @source_object = ] 'source_object', [ @column = ] 'column' ]
[ , [ @typetext = ]
'typetext' ]
[ , [ @publication_to_add = ]
'publication_to_add' ]
[ , [ @from_agent = ] from_agent ]
[ , [ @schema_change_script = ]
'schema_change_script' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

exec sp_repladdcolumn 'Consultants' , 'uuData5',
'BIT NOT NULL DEFAULT ((0))'
,
'all'
,
null,

0
,
0
,
0

exec sp_repldropcolumn 'Consultants', 'uuData5

Note: DDL commands can only be executed at the root Publisher, not at any of the republishing Subscribers.

This procedure should not be used on columns with data types that were introduced in SQL Server 2005 or SQL Server 2008.

20. IF LookUp values are Not Deleting, Then Execute the below Query on the Database

DELETE
Lookup
WHERE
(((
LookupFieldName+ DisplayOrder+LTRIM(RTRIM(LookupValue ))) In
( SELECT LookupFieldName +DisplayOrder+LTRIM(RTRIM(LookupValue))
FROM Lookup As Tmp
GROUP BY LookupFieldName+DisplayOrder+LTRIM(RTRIM(LookupValue ))
HAVING Count (*) > 1
))) AND (LookupValue LIKE ' %')

GO

UPDATE
Lookup SET LookupValue = LTRIM(RTRIM( LookupValue))
WHERE ( LookupValue LIKE ' %')

GO

21. Find the duplicate Email1 and order by DESC

SELECT
Email1
FROM
Consultants
GROUP
BY Email1
HAVING
COUNT (*) > 1
GO

ORDER BY CAST(SUBSTRING(RemIntID, 4, 10) AS INT) DESC
GO

21.1. No Primary Key in Reminders and Duplicate RemintIntID - Delete Duplicate Records

1.  Create a Column VishnuID and set it as Identity Column and Mark as Primary Key.

ALTER
TABLE [dbo].[Reminders] ADD VishnuID int not null identity(1,1) primary key

DELETE Reminders
WHERE
VishnuID IN
(

SELECT
VishnuID
FROM

(

SELECT
TOP (200) max(VishnuID) as VishnuID, RemIntID, ItemIntID, CreateDate, EditDate
FROM
   Reminders
WHERE 
(RemIntID IN
       
(SELECT RemIntID
        
FROM   Reminders AS Reminders_1
        
GROUP BY RemIntID
        
HAVING (COUNT(*) > 1)))

GROUP
BY RemIntID, ItemIntID, CreateDate, EditDate
)
TEMP
)

21.2. Easy way of DELETING complex query (RAM)

WITH cte as
(

SELECT
ROW_NUMBER() OVER(Partition By ApptType,ApptSubType, StartDateTime, EndDateTime,ItemIntID,Subject,UserIDs ORDER BY CreateDate ASC) as Dup,Reminders.RemIntID,Reminders.ApptType,Reminders.ApptSubType,Reminders.StartDateTime,Reminders.EndDateTime,Reminders.ItemIntID,dbo.XCBO_GetName(Reminders.ItemIntID) as Name,Reminders.Subject,dbo.XCBO_TrimDelimiter(Reminders.UserIDs) as UserIDs, Reminders.CreateDate
FROM
Reminders
WHERE
(Reminders.RemType='Appointment') AND (Reminders.StartDateTime < DateAdd(d,1,GETDATE()) OR IsDate(Reminders.StartDateTime)=0)
AND
((3=3)) AND ((Reminders.UserIDs LIKE '%,jjinright,%')) AND Reminders.Done=0 AND LEN(ApptSubType) > 0
)


SELECT
* FROM cte
WHERE
Dup = 1 

22. when we update the date field from out side the cBiz, then convert it to Small Date Time and Update it.

CAST( GETDATE() AS SMALLDATETIME)

22.1. Getting Date From DateTime.

SELECT DATEADD (dd, 0, DATEDIFF( dd, 0 , GETDATE()))

22.2. Delete the CnadidateFetch setting from the database.

DELETE Documents
WHERE
ItemIntID = 'JC00000003' AND DocType = 'Config' AND DocSubType = 'JCConfig' AND DocName = 'cf_settings.xml'

23. cBizOne Date Stamp.

SELECT  '*** ' + ISNULL('Admin', '') + ' *** ' + CONVERT(NVARCHAR(20),GETDATE(),100) + CHAR(13) + CHAR(10)

24. RaisError from Reminders Table.

CREATE TRIGGER [dbo].[CBO_Reminders]
ON [dbo] .[Reminders]
FOR update
AS

BEGIN

             RAISERROR ('HI FROM REMINDERS' , 16, 1)

END

24.1. Not Include the custom trigger for replication.

CREATE TRIGGER [dbo].[Trig_RecruiterAssigned]
ON [cBizOne] .[dbo].[Requirements]
FOR INSERT
NOT FOR REPLICATION
AS
........

25. Unable to delete Maintenance plane and Job.

SELECT * FROM sysmaintplan_subplans

SELECT * FROM [msdb].[dbo].[sysmaintplan_log]
WHERE
subplan_id = 'FBD49A45-8A46-4932-9A4B-AAB25BDBFB11'

DELETE [msdb].[dbo].[sysmaintplan_log]
WHERE subplan_id = 'FBD49A45-8A46-4932-9A4B-AAB25BDBFB11'

DELETE [msdb].[dbo].[sysmaintplan_subplans]
WHERE subplan_id = 'FBD49A45-8A46-4932-9A4B-AAB25BDBFB11'

26. For Nvarchar(Max) I am only getting 4000 characters in TSQL?

SET @sql1 = 'ASDASDASDASD.....'

You have declared this as nvarchar(max) which allows 2GB of data so it will store 2GB.

What is happening:

  • The datatype is not yet nvarchar(max) until assignment to @sql1
  • Before that, it's a collection of strings, each less than 4000 (constants)
  • You are concatenating short constants with short variables (short = < 4000)
  • So you have 4000 characters put into @sql1

So, you have make sure you have nvarchar(max) on the right hand side.

One idea. The 2nd line concatenates nvarchar(max) with a constant = nvarchar(max)

SET @SQL1 = '' 
                        SET @SQL1 = 
                    @SQL1 + 'SELECT DISTINCT Venue...     ....
                 

It's no different to the integer division that happens in every language.

HELP: http://stackoverflow.com/questions/1371383/for-nvarcharmax-i-am-only-getting-4000-characters-in-tsql

27. Date Diff (dd:hh:mm:ss)

(trim(convert(char(10), (DATEDIFF( SECOND, Requirements.CreateDate ,MLinkInfo.DateTime) / 86400))) + ':' + right('0' + trim(convert(char(2), ((DATEDIFF( SECOND, Requirements.CreateDate ,MLinkInfo.DateTime) % 86400) / 3600))), 2 ) + ':' +
right('0' + trim (convert (char (2), ((( DATEDIFF( SECOND, Requirements.CreateDate ,MLinkInfo.DateTime) % 86400) % 3600) / 60) % 60)), 2 ) + ':' +
right('0' + trim (convert (char (2), ((( DATEDIFF( SECOND, Requirements.CreateDate ,MLinkInfo.DateTime) % 86400) % 3600) % 60) % 60)),2 )) AS DDIFF

28. IMP IMP IMP Identity Column with Select statement and Building the Temp table with Select statement

SELECT *, IDENTITY( int ) AS idcol INTO #newtable
FROM Consultants

SELECT *
FROM #newtable

OR

CREATE TABLE #OpenReq(RowNumber INT IDENTITY, ReqIntID_T NVARCHAR(10))

INSERT INTO #OpenReq(ReqIntID_T)
SELECT Requirements.ReqIntID
FROM Requirements
WHERE Requirements.Archived = 0 AND
(
Requirements.ClosedDate > GETDATE() OR IsDate(Requirements.ClosedDate)=0)

SELECT *
FROM #OpenReq

DROP TABLE #OpenReq

29. When Use Top Use Order By (Delete Duplicate Candidates based on Email1.)

USE [1Demodatabase]
GO

-- Keep Old Record and Delete all Other Duplicate.

WITH
DuplicateRows_Table
AS

(

      
SELECT EMail1 AS Duplicate_Row_ID
      
FROM dbo.Consultants
      
WHERE (LEN(ISNULL(EMail1, '')) > 0)
      
GROUP BY EMail1
      
HAVING COUNT(1) > 1

),
RowsToDelete_Table
AS

(

      
 SELECT ROW_NUMBER() OVER(Partition By DRT.Duplicate_Row_ID ORDER BY Temp.CreateDate ASC) AS 'RowNumber', Temp.ConsIntID, Temp.CreateDate
      
 FROM Consultants Temp, DuplicateRows_Table DRT
      
 WHERE (Temp.EMail1 = DRT.Duplicate_Row_ID)

)


SELECT
*
--DELETE TOP (10)

FROM
Consultants
WHERE
ConsIntID IN
      
(
             
SELECT ConsIntID
             
FROM RowsToDelete_Table
             
WHERE (RowNumber != 1)
      
)

29.1. DELETE Duplicate LookUp entries (Keep first one duplicate entry and delete other)

WITH DuplicateRows_Table
 
AS

 
(
      
SELECT LookupFieldName +DisplayOrder+LTRIM(RTRIM(LookupValue)) as ID
      
FROM Lookup As Tmp
      
GROUP BY LookupFieldName+DisplayOrder+LTRIM(RTRIM(LookupValue ))
      
HAVING Count (*) > 1
 
), RowsToDelete_Table
 
AS

 
(
      
SELECT ROW_NUMBER() OVER(Partition By LookupFieldName +DisplayOrder+LTRIM(RTRIM(LookupValue)) ORDER By LookupFieldName) AS 'RowNumber',
       LookupFieldName + DisplayOrder+LTRIM(RTRIM(LookupValue)) as ID
      
FROM Lookup
      
WHERE (LookupFieldName +DisplayOrder+LTRIM(RTRIM(LookupValue))) IN (SELECT ID FROM DuplicateRows_Table)
)


DELETE
RowsToDelete_Table
WHERE RowNumber != 1 

30. To Know the number of Triggers on the Databaseebasee (DB All Triggers)

SELECT s2. [name] tablename, s1.[name] triggername ,
CASE
WHEN s2 .deltrig = s1. id THEN 'Delete'
WHEN s2.instrig = s1. id THEN 'Insert'
WHEN s2.updtrig = s1. id THEN 'Update'
END 'TriggerType', 'S1', s1.*, 'S2', s2.*
FROM
sysobjects s1 JOIN sysobjects s2 ON s1. parent_obj = s2 .[id]
WHERE
s1. xtype = 'TR'

OR

SELECT * FROM sys./span>triggers WHERE is_disabled = 0

30.1. Run following query to find the jobs which are currently running.

exec msdb..sp_get_composite_job_info @execution_status=1

30.2. Currently Jobs on a Database.

SELECT database_name, name as JobName
FROM
msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps       
ON
job.job_id = steps.job_id
WHERE
job.enabled = 1 AND
database_name = 'Exl_VishnuTest1'

ORDER
BY database_name  

31. COALESCEE

DECLARE @Values VARCHAR(1000)
SELECT @Values = COALESCE(@Values + ', ', '') + Consultants.DisplayName
FROM
Consultants

SELECT @Values

--RESULT: A AhamedHajaShareef, A Arun, A Asharaf Ali, A B Saravanan, A Babu

32. Change the DataBase Name and Logical Name

ALTER DATABASE cBizOne1 MODIFY NAME = cBizOne
GO

ALTER DATABASE [cBizOne] MODIFY FILE ( NAME=N'cBizOne1' , NEWNAME =N'cBizOne_Data' )
GO

ALTER DATABASE [cBizOne] MODIFY FILE ( NAME=N'cBizOne1_Log' , NEWNAME=N'cBizOne_Log' )
GO

32. Free up memory for SQL Server by cleaning up its cache

DBCC FREESESSIONCACHE
DBCC
FREEPROCCACHE

33. Time consuming query (you can control this query with Companies.UserField input as ‘YES’)

SELECT COUNT(*)
FROM

(

SELECT
DISTINCT (ReqIntID+CompanyIntID+ ConsIntID+RemIntID +MLinkIntID) AS ID
FROM
dbo.Companies,dbo .Consultants,dbo. Reminders,dbo .MLinkInfo,dbo. Requirements
WHERE
Companies. UserField1 = 'YES'
)
T
WHERE
ID LIKE '%VISHNU%'

34. Important Logic Please Go Through (Rows to Columns)

SELECT Month1,
ISNULL(SUM(case when What='Sourced' then XCount end),0) as Sourced,
ISNULL(SUM(case when What='InitialInterviews' then XCount end),0) as InitialInterviews,
ISNULL(SUM(case when What='AdvancedInterviews' then XCount end),0) as AdvancedInterviews,
ISNULL(SUM(case when What='Submitted' then XCount end),0) as Submitted
FROM

(
SELECT (Datename(MONTH, Consultants.CreateDate ) + Datename (YEAR , Consultants.CreateDate)) AS Month1 , COUNT(*) AS XCount, max('Sourced' ) as What

....

)TempTable
GROUP
BY Month1

34.1. Important Logic Please Go Through (Rows to Columns for StringData)

SELECT
MAX(CASE WHEN ColumnName = '_1' THEN Data END ) _1,
MAX(CASE WHEN ColumnName = '_2' THEN Data END ) _2
FROM
(
SELECT 'First' as Data , '_1' as ColumnName
UNION ALL
SELECT 'Second' as Data , '_2' as ColumnName
)TempTable

35. DISABLE/ENABLE ALL TRIGGER IN A DATABASE

Example1:
-- DISABLE ALL TRIGGER IN A DATABASE
DECLARE @SQLMessage NVARCHAR(MAX)
SET @SQLMessage = ''

SELECT @SQLMessage = @SQLMessage + 'DISABLE TRIGGER ALL ON ' + TABLE_SCHEMA + '.' + TABLE_NAME + ';' + CHAR(10) + CHAR(13) from INFORMATION_SCHEMA.TABLES

EXEC(@SQLMessage)

-- ENABLE ALL TRIGGER IN A DATABASE
DECLARE @SQLMessage NVARCHAR(MAX)
SET @SQLMessage = ''

SELECT @SQLMessage = @SQLMessage + 'ENABLE TRIGGER ALL ON ' + TABLE_SCHEMA + '.' + TABLE_NAME + ';' + CHAR(10) + CHAR(13) from INFORMATION_SCHEMA.TABLES

EXEC(@SQLMessage)

Example2:
-- DISABLE/ENABLE ALL TRIGGER ON One Table
DISABLE TRIGGER ALL ON dbo.Reminders;
ENABLE TRIGGER ALL ON dbo.Reminders;

Example3:
-- DISABLE/ENABLE ALL TRIGGER ON Database At Once
EXEC sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER ALL"
EXEC sp_msforeachtable "ALTER TABLE ? ENABLE TRIGGER ALL"

35.1. To copy customizations from one database to another(Same Server)

-- Deleting Customization and Stylesheets
DELETE [exl_geckosmith].[dbo].[Documents]
WHERE ItemIntID = 'CF00000000'

DELETE [exl_geckosmith].[dbo].[Documents]
WHERE ItemIntID = 'CF00000001'

--- Customize.zip
INSERT INTO [exl_geckosmith].[dbo].[Documents] (ItemIntID, DocType, DocSubType, DocName, DocContent, DocText, UserIDs, Private, CreateDate, EditDate, MergeDate, Field1, Field2, Field3)
SELECT ItemIntID, DocType, DocSubType, DocName, DocContent, DocText, UserIDs, Private, CreateDate, EditDate, MergeDate, Field1, Field2, Field3
FROM [exl_geckoscott].[dbo].[Documents]
WHERE ItemIntID = 'CF00000000'

--- Stylesheets.zip
INSERT INTO [exl_geckosmith].[dbo].[Documents] (ItemIntID, DocType, DocSubType, DocName, DocContent, DocText, UserIDs, Private, CreateDate, EditDate, MergeDate, Field1, Field2, Field3)
SELECT ItemIntID, DocType, DocSubType, DocName, DocContent, DocText, UserIDs, Private, CreateDate, EditDate, MergeDate, Field1, Field2, Field3
FROM [exl_geckoscott].[dbo].[Documents]
WHERE ItemIntID = 'CF00000001'

35.1.1 To copy customizations from one database to another(Auto Create Table)(Kris Ask this)

SELECT * INTO Documents_Temp  FROM Documents WHERE ItemIntID LIKE 'CF%'

Now Generate Script and Select Data Only and QueryWindow

Replace the Documents_Temp to Documents in the Query and Execute at target Database.

35.1.2 Build Temp Table form SELECT Command(Transwar data from one server to another server)(Kris gives this work)

SELECT 'SELECT * INTO #VishnuTest1 FROM ('
UNION
ALL
SELECT
'SELECT ''' + CAST(UserField10 AS NVARCHAR(MAX)) + ''' as UserField10, ''' + UserIDs + ''' as UserIDs, ''' + CAST(Child_Person_Number AS NVARCHAR(MAX)) + ''' as Child_Person_Number, ''' + CandFirstName + ''' as CandFirstName, ''' + CandLastName + ''' as CandLastName, ''' + RecruiterFirstName + ''' as RecruiterFirstName, ''' + RecruiterLastName + ''' as RecruiterLastName UNION ALL '
FROM
CandidateUserIDs
UNION
ALL
SELECT
') Temp' 

35.2. Issues with Recurring annual events

1. Delete all the existing annual events

DELETE
Reminders
WHERE
SUBJECT like 'Date of Birth%' OR RemField = 'DOB'

2. Now once again go to cBizOne Tools – Options – Calendar unset and save and close cBizOne and reset the Annual/Onetime Events (Since this Events uses computer regestry to create them).

OR

1. Keep Old Record and Delete all Other Duplicate

WITH DuplicateRows_Table
 
AS

 
(
        
SELECT ItemIntID + UserIDs as Duplicate_Row_ID
        
FROM   Reminders
        
WHERE (SUBJECT like 'Date of Birth%' OR RemField = 'DOB') AND Done = 0
        
GROUP BY ItemIntID + UserIDs
        
HAVING (COUNT(*) > 1)
 
), RowsToDelete_Table
 
AS

 
(
        
SELECT ROW_NUMBER() OVER(Partition By DRT.Duplicate_Row_ID ORDER BY Temp.CreateDate ASC)  AS 'RowNumber', DRT.Duplicate_Row_ID, Temp.RemField,Temp.RemIntID, Temp.CreateDate
        
FROM Reminders Temp, DuplicateRows_Table DRT
        
WHERE (Temp.ItemIntID + Temp.UserIDs = DRT.Duplicate_Row_ID) AND

             
 
(Temp.SUBJECT like 'Date of Birth%' OR Temp.RemField = 'DOB') AND Temp.Done = 0
 
)

 
SELECT * 
 
--DELETE TOP (10)
 
FROM Reminders 
 
WHERE RemIntID IN 

(

       
SELECT RemIntID
       
FROM RowsToDelete_Table
       
WHERE (RowNumber != 1)

)

35.3. Complete the Old Reminders (Done = 1)

select distinct(datepart(year,RemDateTime)),count(*)
from
Reminders
where
Remtype = 'Appointment' and Done = 0
group
by datepart( year, RemDateTime)

Go

-- First Test the above and give the appropriate old year in the
-- below code and execute

update
Reminders set Done = 1, RemAlarm = 0
where
Remtype = 'Appointment' and Done = 0 and
datepart( year, RemDateTime) = '1800' --<--- Give the correct value here

35.3.1 On ‘My Daily Call/Task List’ Complete all items on or before 10/26/15

SELECT RemType, ApptType, Done, RemAlarm, StartDateTime, RemDateTime, UserIDs
FROM
Reminders
WHERE
(Reminders.RemType = 'Appointment') AND
     
(Reminders.ApptType='Call' OR Reminders.ApptType='Task') AND
   
 
(Done = 0) AND (StartDateTime < '2015-10-26') AND (UserIDs = ',Keith Fall,')

UPDATE
Reminders SET Done = 1, RemAlarm = 0
WHERE
(Reminders.RemType = 'Appointment') AND
     
(Reminders.ApptType='Call' OR Reminders.ApptType='Task') AND
   
 
(Done = 0) AND (StartDateTime < '2015-10-26') AND (UserIDs = ',Keith Fall,')

35.4. Update Companies WebPage from Contact WebPage

UPDATE Companies SET Companies.WebPage = Contacts.WebPage
FROM
Contacts, Links
WHERE
(Companies .CompanyIntID = Contacts.LinkToIntID) AND
(LEN(ISNULL(Companies. WebPage,''))=0 ) AND
(
LEN( Contacts.WebPage )>0) AND (LEN (Contacts.LinkToIntID)> 0) AND
(
Links.FromID = Contacts.ContactIntID AND Links. ToID = Contacts .LinkToIntID AND Links.Type = 1 AND Links.SubType = 1)

36. (TSQL) Escape Underscore in Like (IMP)

SELECT * FROM Table WHERE Column LIKE '_a_'
The above code will generate results that has any one character before and after 'a' such as:
mac
cat
sad

SELECT * FROM Table WHERE Column LIKE '%[_]a[_]%'
The above code will generate results such as:
in_a_house
she_is_a_mother
make_a_living

36.1 (TSQL) Escape Underscore in Like (IMP)

DECLARE @command nvarchar (2000)
SELECT
@command = 'use [?]

IF(''?'' like ''cbiz[_]%'')
BEGIN

IF (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''Users'' AND COLUMN_NAME = ''AppPermissions'') = 0

SELECT ''?''

END '

EXEC sp_MSforeachdb @command

37. LookUp Value for a field in a Dynamic View (Create a Candidate with display name (Consultants.PrimarySkills))

<View>
<ID>uuLookup</ID>
<Caption>Lookup</Caption>
<SQL>SELECT Consultants.ConsIntID,Consultants.DisplayName,Lookup.LookupValue,Lookup.LookupDesc FROM Consultants,Lookup WHERE (Consultants.DisplayName = Lookup.LookupFieldName) AND (Consultants.Private=False OR Consultants.UserIDs LIKE [LoggedInUser])</SQL>
<Properties>54269</Properties>
</View>

38. Format MONEY DataType (Remove .00)

DECLARE @MONEY MONEY

SET @MONEY = 222

SELECT @MONEY

-- OUT PUT 222.00

SELECT REPLACE(CONVERT(VARCHAR(20), @MONEY, 1),'.00','')

-- OUT PUT 222

39. Make Mandatory field in cBizOne

<Usage>JobTitle,,,,?*,"E: Please enter Job Title.",C0C0FF</Usage>

40. cBizOne Command Arguments

cBizOne /d "c:\Program Files\cBiz\cBizData" /db DSN=cBizOne;UID=cbiz_test;PWD=cbiz_test; /lod yes /f Contacts /hosteddb no /u username /p  password

41. Find the Existing SiteID

SELECT DISTINCT(SiteID) AS SiteID
FROM (
SELECT
DISTINCT(SUBSTRING(ConsIntID,3,1)) AS SiteID
FROM
dbo.Consultants
UNION ALL
SELECT
DISTINCT(SUBSTRING(CompanyIntID,3,1)) AS SiteID
FROM
dbo.Companies
UNION
ALL
SELECT
DISTINCT(SUBSTRING(ContactIntID,3,1)) AS SiteID
FROM
dbo.Contacts
UNION
ALL
SELECT
DISTINCT(SUBSTRING(RemIntID,3,1)) AS SiteID
FROM
dbo.Reminders
UNION
ALL
SELECT
DISTINCT(SUBSTRING(ReqIntID,3,1)) AS SiteID
FROM
dbo.Requirements
UNION
ALL
SELECT
DISTINCT(SUBSTRING(FROMID,3,1)) AS SiteID
FROM
dbo.links
UNION
ALL
SELECT
DISTINCT(SUBSTRING(TOID,3,1)) AS SiteID
FROM
dbo.links
)
TEMP

42. You can access the web2.0 Exelare app by doing the following:

1. http://cbiz-srv3.network80.com/Exelare

2. Enter the following details:

CompanyID: cbiz_test2
cBiz username:Test
Password:test

Note: Also, you can have both cBizOne and Exelare working simultaneously. Any changes made in Exelare will be reflected in cBizOne and vice-versa.

43. How To Obtain The Size Of All Tables In A SQL Server Database (DB All Row Count)

--Reports and corrects pages and row count inaccuracies in the catalog views.
--These inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.
--DBCC UPDATEUSAGE('Exl_VishnuTest1', 'dbo.Documents') WITH COUNT_ROWS ;

SET NOCOUNT ON

DBCC UPDATEUSAGE(0)

-- DB size.
EXEC sp_spaceused

-- Table row counts and sizes.
CREATE TABLE #t
(
    [name] NVARCHAR(128),
    [rows] CHAR(11),
    reserved VARCHAR(18),
    data VARCHAR(18),
    index_size VARCHAR(18),
    unused VARCHAR(18)
)

INSERT #t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''

SELECT *
FROM   #t
Order by Name

-- # of rows.
SELECT SUM(CAST([rows] AS int)) AS [rows]
FROM   #t
 
DROP TABLE #t

43.-0. Get Each Column size in MD and GB.

-- Specify the table name
DECLARE
@TableName NVARCHAR(128) = 'Consultants';
DECLARE
@ColumnName NVARCHAR(128);
DECLARE
@SQL NVARCHAR(MAX) = '';

DECLARE
column_cursor CURSOR FOR
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @TableName;

OPEN
column_cursor;
FETCH
NEXT FROM column_cursor INTO @ColumnName;
WHILE
@@FETCH_STATUS = 0
BEGIN

   
SET @SQL = @SQL +
       
'SELECT ''' + @ColumnName + ''' AS ColumnName, ' +
       
' SUM(CAST(DATALENGTH([' + @ColumnName + ']) AS BIGINT)) / 1048576.0 AS Size_MB ' +
       
'FROM ' + @TableName + ' UNION ALL ';
   
FETCH NEXT FROM column_cursor INTO @ColumnName;
END
CLOSE
column_cursor;
DEALLOCATE
column_cursor;
-- Remove the trailing "UNION ALL" from the SQL

SET
@SQL = LEFT(@SQL, LEN(@SQL) - LEN(' UNION ALL '));
--print @SQL


CREATE
TABLE #All_ColumnSize
(

   
ColumnName
NVARCHAR(128),
   
Size_MB
REAL
)

-- Execute the dynamic SQL

INSERT
#All_ColumnSize EXEC sp_executesql @SQL;
SELECT ColumnName, Size_MB, Size_MB/1024 AS Size_GB
FROM

(

SELECT
ColumnName, CONVERT(decimal(18, 1), ROUND(ISNULL(Size_MB, '0'), 1)) AS Size_MB FROM #All_ColumnSize
)
TT
WHERE
Size_MB > 0
ORDER
BY Size_MB DESC

DROP
TABLE #All_ColumnSize

43.-1. Export Database Check All Table Count (Good use of Exec() command).

SET
QUOTED_IDENTIFIER OFF
DECLARE
@SQL_Message NVARCHAR(MAX), @OriginalDatabase NVARCHAR(100), @ExportDatabase NVARCHAR(100)
SET
@OriginalDatabase = '[cBiz_redseal]'
SET
@ExportDatabase = '[cBiz_redseal_Export]'
SET
@SQL_Message = "
SELECT '
SELECT ''' + name + ''' as TableName,
(
SELECT COUNT(1) FROM "
+ @OriginalDatabase + ".dbo.' + name + '
) as "
+ @OriginalDatabase + ",
(SELECT COUNT(1) FROM "
+ @ExportDatabase + ".dbo.' + name + '
) as "
+ @ExportDatabase + ",

ISNULL(
CAST((
SELECT ''True''
WHERE ( (SELECT COUNT(1) FROM "
+ @OriginalDatabase + ".dbo.' + name + ') =
(SELECT COUNT(1) FROM "
+ @ExportDatabase + ".dbo.' + name + ')
)
) AS CHAR(5))
,''FALSE'') as Result'
FROM "
+ @OriginalDatabase + ".dbo.sysobjects
WHERE xtype='U'

UNION ALL

SELECT '
SELECT ''' + name + ''' as TableName,
0 as "
+ @OriginalDatabase + ",
(
SELECT COUNT(1)
FROM "
+ @ExportDatabase + ".dbo.' + name + '
) as "
+ @ExportDatabase + ", ''New'' as Result'
FROM "
+ @ExportDatabase + ".dbo.sysobjects
WHERE xtype='U' AND (name IN ('ContactInfo','RMLinks'))
"

--print @SQL_Message

CREATE
TABLE #WorkingData( col1 NVARCHAR(MAX ))
INSERT
INTO #WorkingData
EXEC
(@SQL_Message )

SELECT
@SQL_Message =
STUFF
(
(
SELECT ' UNION ALL ' + [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](Col1)
FROM
#WorkingData
ORDER
BY col1 FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)')
,
1, 11, '')

CREATE
TABLE #ResultData(TableName NVARCHAR(250), cBiz_redseal BIGINT, cBiz_redseal_Export BIGINT, Result NVARCHAR(10))
INSERT
INTO #ResultData
EXEC
(@SQL_Message)

SELECT
* FROM #ResultData WHERE (Result != 'New' )
UNION
ALL
SELECT
'Total: ', SUM (cBiz_redseal), SUM(cBiz_redseal_Export ), '' FROM #ResultData WHERE (Result != 'New')
UNION
ALL
SELECT
* FROM #ResultData WHERE (Result = 'New')

DROP
TABLE #WorkingData
DROP
TABLE #ResultData
SET
QUOTED_IDENTIFIER ON

43.0. Find Database .mdf and .ldf Size with file physical location.

SELECT DB_NAME( database_id) AS DatabaseName,Name AS Logical_Name ,Physical_Name, (size* 8)/ 1024 SizeMB
FROM
sys.master_files
WHERE
DB_NAME( database_id) = 'Exl_VishnuTest1'

43.1. Query 1 can be used to find out count of memory pages loaded for each database.

SELECT COUNT(*)AS cached_pages_count
,CASE database_id
WHEN 32767 THEN 'ResourceDb'
ELSE db_name(database_id)
END AS database_name
FROM
sys.dm_os_buffer_descriptors
GROUP
BY db_name(database_id) ,database_id
ORDER
BY cached_pages_count DESC;

43.2. How To Pass the EXEC value to Variable (IMP IMP)

DECLARE @Rank INT

CREATE TABLE #Value ( Column1 INT )

INSERT #Value EXEC('SELECT 3')

SELECT @Rank = Column1 FROM #Value

SELECT @Rank

DROP TABLE #Value

44. cBizOne Dashboard with Groups as UsetID's

Give the following in the EntitiesCustom:

<AddTab Caption="Custom Dashboard" URL="customdashboard.htm" Groups="Departments:Sales"/>

45. Remove the Space before and after from an Email1

--Consultants
UPDATE
Consultants SET EMail1 = LTRIM(RTRIM(EMail1))
WHERE
(LEN (EMail1)>0) AND
((EMail1 LIKE ' %') OR ( EMail1 LIKE '% '))
GO

--Contacts
UPDATE
Contacts SET EMail1 = LTRIM(RTRIM(EMail1))
WHERE
(LEN (EMail1)>0) AND
((
EMail1 LIKE ' %') OR (EMail1 LIKE '% '))
GO

46. One More Contact to Requirement

ALTER TABLE Requirements ADD uuContact NVARCHAR( 60)

Add the below text in RequirementsTLA.xml:

<LinkToID>
<ID>RQCN1002</ID>
<Link>Requirement</Link>
<To>Contact</To>
<Type>1002</Type>
<SubType>1</SubType>
<MenuCaption>Link [[Link]] to Selected [[To]] (Source Name)</MenuCaption>
<FormCaption>Link [[SelectedName]] to a [[To]] (Source Name)</FormCaption>
<Description>Description</Description>
<SearchFields>DisplayName,CompanyName,EMail1</SearchFields>
<ViewSQL>SELECT ContactIntID,DisplayName,CompanyName,EMail1 FROM Contacts WHERE Archived=False AND (Private=False OR UserIDs LIKE [LoggedInUser])
ORDER BY DisplayName,CompanyName
</ViewSQL>
<LinkedItemDisplayFields>DisplayName,CompanyName</LinkedItemDisplayFields>
</LinkToID>

Add the below text in RequirementsFields.xml:

<XField><ID>uuContact</ID>
<Properties>292733</Properties>
<Caption>Contact:</Caption>
<ListCaption>Contact</ListCaption>
<DefaultValue></DefaultValue>
<Usage>ContactName,LinkToIDRQCN1002</Usage>

NOTE:

1. This New contact will create a link in Links Table only.

2. We have to adjust the xTabs and Reports code by using Type = 1002 and SubType = 1 or else it will reflect the submissions twice as we have 2 contact to a requirement

3. This feature will remove the "Merge Duplication" option.

46.1. Only Caption on the cBizForm

<XField>
<ID>uuFieldServices</ID>
<Properties>893</Properties>
<Control> <ID>uuFieldServices</ID>
<CType>TextBox</CType>
<TabNumber>6</TabNumber>
<Left>600</Left>
<Top>250</Top>
<Width>4255</Width>
<Height>195</Height>
<Locked>True</Locked>
<BackColor>-2147483633</BackColor>
<MultiLine>False</MultiLine>
 <ScrollBars>0</ScrollBars>
<BorderStyle>0</BorderStyle>
<FontBold>True</FontBold>
<Text>Field Services:</Text>
</Control>
</XField>

46.2. Trigger Is Not Firing For Bulk Records Update (IMP)

http://www.dbforums.com/microsoft-sql-server/857888-triggers-dont-fire-mass-deletes-updates.html 

Most people don't write triggers to handle multi record updates. A trigger acts on a batch which could contain one or more records.

Note: If you are using any update command then don't use any variables in it.
Eg:

IF @isPrimary = 1
BEGIN
UPDATE ContactInfo
SET isPrimary = 0
WHERE ContactID = @ContactID
AND ContactInfoID <> @ContactInfoID
END

Update ContactInfo
set ContactInfo.isPrimary = 0
from ContactInfo
join insrted on ContactInfo.ContactID = inserted.ContactID
 where ContactInfo.ContactInfoID <> inserted.ContactInfoID
and inserted.isPrimary = 1

47. "Today", "This Week", "This Month" Date and time at 00:00:00

-- Today

select DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0 )
select
DATEADD (d, DATEDIFF(d, 0, GETDATE()), 1)

--This Week

SELECT DATEADD(WK, (DATEDIFF(DAY, 0, GETDATE())/7), 0)
SELECT DATEADD(WK, (DATEDIFF(DAY, 0, GETDATE())/7)+1, 0)

--This Month

select DATEADD(month, DATEDIFF(month , 0, GETDATE()), 0)
select
DATEADD (month , 1, DATEADD(month, DATEDIFF (month , 0, GETDATE()), 0))

OR

--This Month

select DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
select
DATEADD(SECOND, -1, DATEADD(month, 1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)))

48. T-SQL: Joins Explained

-- INNER JOIN (Just matches)
-- so total rows will be number of matched records

-- LEFT JOIN (All records from left table, NULLs in the right table if no match)
-- so total rows will be number of records in the left table (tblA)

-- RIGHT JOIN (All records from the right table, NULLs in the left table if no match)
-- so total rows will be number of records in the right table (tblB)

-- FULL JOIN (all records from both tables with matches or not)
-- so total rows will be number of rows in left table + number of rows in right table - number of exact matches)

-- CROSS JOIN (cartesian product of both tables)
-- total rows of left table * right table
Help Link

48.0. Excellent Query Optimization Through having JOINS in the FROM block

We can Improve the Query Performance by having Joins in the from Block.
Ram Hint: From Block will Execute first.

Below Query Performance is Ammazing, I used the help of above Image and developed the Query.

Example:

SELECT Requirements.ReqIntID,Requirements.ReqID as Requirement,Requirements.JobTitle,Requirements.Location,
      
Contacts.ContactIntID,Contacts.DisplayName as Contact,Contacts.LinkToIntID,Contacts.CompanyName as Company,
      
'' as ConsIntID,'' as Consultant,'No' as Type,'' as SubType,
      
Requirements.CreateDate AS DateAndTime,Requirements.UserIDs  

FROM
Requirements LEFT JOIN Contacts ON Requirements.LinkToIntID=Contacts.ContactIntID
WHERE
(Requirements.Archived = 0) AND
      
(Requirements.ClosedDate > GETDATE() OR IsDate(Requirements.ClosedDate)=0) AND
      
((SELECT COUNT(1) FROM dbo.[XCBO_PermReqsPipeLineDetailed] P WHERE (P.ReqIntID_T = Requirements.ReqIntID)) = 0)

SELECT Requirements.ReqIntID,Requirements.ReqID as Requirement,Requirements.JobTitle,Requirements.Location,
      
Contacts.ContactIntID,Contacts.DisplayName as Contact,Contacts.LinkToIntID,Contacts.CompanyName as Company,
      
'' as ConsIntID,'' as Consultant,'No' as Type,'' as SubType,
      
Requirements.CreateDate AS DateAndTime,Requirements.UserIDs  

FROM
dbo.[XCBO_PermReqsPipeLineDetailed] P
      
RIGHT JOIN (Requirements LEFT JOIN Contacts ON Requirements.LinkToIntID=Contacts.ContactIntID) ON (P.ReqIntID_T = Requirements.ReqIntID)
      
WHERE (Requirements.Archived = 0) AND

      
(Requirements.ClosedDate > GETDATE() OR IsDate(Requirements.ClosedDate)=0) AND
      
(P.ReqIntID_T IS NULL)

Function LInk: XCBO_PermReqsPipeLineDetailed.sql.

48.1. Cross Apply and Outer Apply

SQL Server 2005 introduced the Apply operator like a join clause, which allows joining between two table expressions. The difference between Join and Apply operator becomes evident when we have a table-valued expression on the right side and want this table-valued expression to be evaluated for each row from the left table expression.

Example:
DROP TABLE #newtable
SELECT
* INTO #newtable
FROM

(

SELECT
10  AS  empId, 'AL'  AS  empState, '1/1/2012'  AS  empStDate, '12/1/2012'  AS  empEndDate
UNION
ALL
SELECT
10  AS  empId, 'FL'  AS  empState, '2/1/2012'  AS  empStDate,  '2/1/2013'  AS  empEndDate
UNION
ALL
SELECT
15  AS  empId, 'FL'  AS  empState, '3/20/2012'  AS  empStDate, '1/1/2099'  AS  empEndDate
)
TT

SELECT
* FROM #newtable

select
empid, col,  value from #newtable
cross
apply
(

select
'empstate', empstate union all
select
'empstdate', convert(varchar(10), empstdate, 120) union all
select
'empenddate', convert(varchar(10), empenddate, 120)
)
c (col, value)

Help Link

48.2. Table Value Function with Cross Apply

SELECT IDENTITY( int ) AS RowNo, A.EntityName, A.StatusName, A.ProcessSinceDate, G.RemReqIntID, G.UserIDs INTO #AutoScheduleReminders
FROM
#AutoScheduleInfo A Cross apply dbo.CBO_GetEntityLatestStatus(A.EntityName,A.StatusName,A.ProcessSinceDate) G

49. Concatenate row values T-SQL

Attention:
FOR
XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') - Will Not Work with SET QUOTED_IDENTIFIER OFF

FOR XML PATH('') - Will Work with SET QUOTED_IDENTIFIER OFF, but NewLine(CHAR(13) + CHAR(10)) will be generated to strange symbols, Replace it with ('')


Example 1.0:

SELECT
STUFF(
(
SELECT ', ' + [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](ID)
FROM
Users
WHERE
RecType = '20'
ORDER
BY Field2 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,
1,2,'')

Example 2.0:Replace the New line with Comma and remove Unnecessary Commas

UPDATE Requirements SET Location =
(
STUFF(
(SELECT ', ' + [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](Data)
FROM dbo.XCBO_fn_ArrayTable(replace(location,char(13)+char(10),', '),',')
WHERE (LEN(Data)>0)
ORDER BY IDX FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,2,'')
)
where datalength(Location)>0 and
(location like '%'+char(13)+char(10)+'%')


Note: By adding ,TYPE you instruct FOR XML PATH to generate the data with the xml data type. Then you can use the type method value to extract the value in the desired data type.

Complete Example:

SELECT Requirements.ReqID,Requirements.JobTitle,Requirements.UserField6,PrimarySkills, Description,Location, UserIDs,
( STUFF((SELECT ', ' + [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](Field2) FROM Users WHERE RecType = '20' AND Requirements.UserIDs LIKE '%,'+ID+',%' ORDER BY Field2 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ) AS EmailIDs
FROM Requirements
WHERE Requirements.Archived = 0
ORDER BY Requirements.ReqID,Requirements.JobTitle

Example 1:

SELECT CAST(((SELECT [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](Subject) + ', '
FROM
Reminders
WHERE
(RemType='Note' AND ApptSubType='PrePriority') AND
((
Reminders.RemIntID) In (SELECT FromID FROM Links WHERE ToID='RQ00000019' AND Type=1 AND SubType =1))
ORDER
BY Subject FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')) AS NVARCHAR(4000))

OutPut:

Client, Partner, Sub Contractor,

Example 2: (Update the QNotes of candidate for othere table with duplicate EmailID's)

UPDATE dbo.Consultants SET Consultants.Notes =
(

SELECT

CAST
((
SELECT
ISNULL(E. [Qnote for cBiz],'') + '  '
FROM
dbo.EmailVishnu E
WHERE
(E.EMAIL = V.EMAIL )
ORDER
BY E.[Qnote for cBiz] FOR XML PATH('')
)
AS NVARCHAR( MAX))
)+
Char (13) + Char(10) + Char(13) + Char( 10) +
ISNULL
(CAST (Consultants.Notes AS NVARCHAR(MAX)), '')
FROM
dbo. EmailVishnu V
where
(LTRIM (RTRIM (Consultants.EMail1)) = LTRIM(RTRIM(V.Email)))

49.0. Use GROUP BY to Concatenate Strings (IMP IMP)

SELECT * INTO #YourTable 
FROM

(

      
SELECT 'CS00000106' AS id, 'WE' AS VALUE
      
UNION ALL
       SELECT 'CS00000106' AS id, 'EE' AS VALUE
       UNION ALL
       SELECT 'CS00000106' AS id, 'DD' AS VALUE
       UNION ALL
       SELECT 'CS00000105' AS id, 'SS' AS VALUE
) T

SELECT
Results.ID,
      
STUFF((
      
SELECT ', ' +
[dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](T.Value)
      
FROM #YourTable T
      
WHERE (T.ID = Results.ID)
      
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
      
,1,2,'') AS NameValues

FROM
#YourTable Results
GROUP
BY Results.ID 

OUT PUT:
ID     NameValues
CS00000105    SS
CS00000106    WE, EE, DD
 

49.1. Querying XML (IMP IMP)

Sample Example 1:

DECLARE @XML XML;
SELECT
@XML =
'<ROOT>
<Customers>
<CustomerId>1111</CustomerId>
<CompanyName>Sean Chai</CompanyName>
<City>NY</City>
</Customers>
<Customers>
<CustomerId>1112</CustomerId>
<CompanyName>Tom Johnston</CompanyName>
<City>LA</City>
</Customers>
<Customers>
<CustomerId>1113</CustomerId>
<CompanyName>Institute of Art</CompanyName>
</Customers>
</ROOT>'
;

SELECT
--R.Node.query('.'),
R
.Node.query('.').value('(/Customers/CustomerId/.)[1]','varchar(100)') AS CustomerID,
R
.Node.query( '.'). value('(/Customers/CompanyName/.)[1]', 'varchar(100)') ASCompanyName

FROM
@XML.nodes('/ROOT/Customers') R(Node);

Sample Example 1.1:

DROP TABLE #AutoScheduleInfo
DECLARE
@XML XML;
SELECT
@XML =
'<SalesAutomation>
<Schedule StatusName="05 - Demo Complete" ReminderDuration="1" StartTime="06:00 AM" EndTime="08:30 AM" AddSubject="test" />
<Schedule StatusName="CompaniesStatus" ReminderDuration="1" StartTime="06:00 AM" EndTime="08:30 AM" AddSubject="test55313131131" />
<Schedule StatusName="Interview" ReminderDuration="1" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" />
</SalesAutomation>'
;

SELECT
--R.Node.query('.'),
IDENTITY
( int ) AS RowNo,
R.Node.value('@StatusName','varchar(100)') AS StatusName,
R.Node.value('@ReminderDuration', 'varchar(100)') ReminderDuration,
R.Node.value('@StartTime', 'varchar(100)') StartTime,
R.Node.value('@EndTime', 'varchar(100)') EndTime,
R.Node.value('@AddSubject', 'varchar(100)') AddSubject INTO #AutoScheduleInfo

FROM
@XML.nodes('/SalesAutomation/Schedule') R(Node); 

SELECT
* FROM #AutoScheduleInfo 

Sample Example 2:

DECLARE @XML XML, @UserIDs NVARCHAR(MAX )

SET
@UserIDs = 'Kris|Admin|Ahmed|Alex|Bob|Bryan|Test'

IF
(LEN(@UserIDs) > 0)
SET
@XML = '<ROOT><Item>' + REPLACE(@UserIDs,'|','</Item><Item>') + '</Item></ROOT>'

SELECT
TempTable.TempColumn.query('.').value('(/Item/.)[1]','NVARCHAR(512)') AS Data
FROM
@XML.nodes('/ROOT/Item') TempTable(TempColumn);

OutPut:

Kris
Admin
Ahmed
Alex
Bob
Bryan
Test

49.2 Delete and Update XML (IMP IMP)

Sample Example 1:
DECLARE
@XML XML
SET
@XML = '<SalesAutomation>
 
<Schedule EntityName="Contacts" StatusName="05 - Demo Complete" ScheduleAfterDays="1" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
 
<Schedule EntityName="Contacts" StatusName="Interview" ScheduleAfterDays="1" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
 
<Schedule EntityName="Contacts" StatusName="Placed" ScheduleAfterDays="2" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
 
<Schedule EntityName="Consultants" StatusName="Placed" ScheduleAfterDays="2" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
 
<Schedule EntityName="Companies" StatusName="Test1" ScheduleAfterDays="2" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
 
<Schedule EntityName="Consultants" StatusName="Interview" ScheduleAfterDays="2" ProcessSinceDate="11/06/1990" StartTime="08:00 AM" EndTime="08:30 AM" AddSubject="" OnceProcessed="No" />
</SalesAutomation>'

SELECT
@XML
DECLARE
@DeleteEntityName NVARCHAR(100) = 'Contacts', @DeleteStatusName NVARCHAR(100) = 'Interview', @UpdateEntityName NVARCHAR(100) = 'Consultants', @UpdateStatusName NVARCHAR(100) = 'Placed', @NewOnceProcessed NVARCHAR(100) = 'Yes'

IF
(@XML.exist('SalesAutomation/Schedule[(@EntityName eq sql:variable("@DeleteEntityName")) and (@StatusName eq sql:variable("@DeleteStatusName"))]') = 1)
SET
@XML.modify('delete SalesAutomation/Schedule[(@EntityName eq sql:variable("@DeleteEntityName")) and (@StatusName eq sql:variable("@DeleteStatusName"))]')

IF
(@XML.exist('SalesAutomation/Schedule[(@EntityName eq sql:variable("@UpdateEntityName")) and (@StatusName eq sql:variable("@UpdateStatusName"))]') = 1)
SET
@XML.modify('replace value of (SalesAutomation/Schedule[(@EntityName eq sql:variable("@UpdateEntityName")) and (@StatusName eq sql:variable("@UpdateStatusName"))]/@OnceProcessed)[1] with sql:variable("@NewOnceProcessed")')
SELECT
@XML

Sample Example 2: Update all attriutes values
-- DECLARE @nodeCount int = @xml.value('count(SalesAutomation/Schedule/@OnceProcessed)','int')

DECLARE
@Node int = 1, @UpdateCount int = @xml.value('count(SalesAutomation/Schedule/@OnceProcessed[.="No"])','int')
WHILE
(@Node <= @UpdateCount)
BEGIN

      
SET @XML.modify('replace value of (SalesAutomation/Schedule/@OnceProcessed[.="No"])[1] with "Yes"')
      
SET @Node = @Node + 1

END

SELECT
@XML
IF
(@UpdateCount >= 1)
      
SELECT 'Do some activity' as Action

50. Search and Replace in a TEXT(NTEXT) column (IMP IMP)

Sample Example:

DECLARE
@FindString NVARCHAR (100),
@ReplaceString
NVARCHAR(100),
@ConsIntID
NVARCHAR( 10),
@TextPointer
VARBINARY (16),
@DeleteLength
INT ,
@OffSet
INT

SET
@FindString = 'Vishnu'
SET
@ReplaceString = 'Vishnu Murthy'
SET
@ConsIntID = 'CS00000095'

SELECT
@TextPointer = Textptr(uuResumeText)
FROM
Consultants
WHERE
( ConsIntID = @ConsIntID )

SET
@DeleteLength = Len(@FindString)
SET
@OffSet = 0
SET
@FindString = '%' + @FindString + '%'

SELECT
@OffSet = Patindex(@FindString, uuResumeText) - 1
FROM
Consultants
WHERE
Patindex(@FindString, uuResumeText) <> 0
AND ( ConsIntID = @ConsIntID )

PRINT
@TextPointer
PRINT
@OffSet
PRINT
@DeleteLength
PRINT
@ReplaceString

UPDATETEXT
Consultants.uuResumeText
@TextPointer
@OffSet
@DeleteLength
@ReplaceString

51. Password Reset

select * from Users
where RecType = '20' and ID = 'Admin'

update
Users set Password='“–‘˜“šÍÏÎÏ'
where RecType = '20' and ID = 'Admin'

update
Users set Password=''
where RecType = '20' and ID = 'Admin'

51.1. Creating Test UserID

INSERT
INTO dbo.Users
VALUES
('20','Test', '0,0','', 1,'26623,1011,1011,1011,1011,1019,1011,1011' ,'','' ,'','' )

51.2. Creating the constraints to ZipCodes table

ALTER
TABLE ZipCodes ALTER COLUMN
ZIPCode
NVARCHAR( 5) NOT NULL
GO

ALTER
TABLE dbo.ZipCodes ADD
CONSTRAINT [aaaaaZIPCode_PK] PRIMARY KEY NONCLUSTERED
([ZIPCode] ) ON [PRIMARY]
GO

52. Update blank CompanyPhone with Top 1 Linked Contact CompanyPhone (IMP IMP)

xupdate Companies set CompanyPhone = NULL
from
Contacts
where
(len(isnull(contacts.LinkToIntID,''))>0) and
(
len(isnull(contacts.companyphone,''))>0) and
(
companies.CompanyIntID = contacts.LinkToIntID) and
(
len(isnull(companies.CompanyPhone,''))=0)
Go


xupdate Companies
set CompanyPhone = NULL
from
Contacts
where
(len(isnull(contacts.LinkToIntID,''))>0) and
(
len(isnull(contacts.DirectPhone,''))>0) and
(
companies.CompanyIntID = contacts.LinkToIntID) and
(
len(isnull(companies.CompanyPhone,''))=0)
Go


xupdate companies
set companies.CompanyPhone = Contacts.CompanyPhone
from
Contacts
where
(len(isnull(contacts.LinkToIntID,''))>0) and
(
len(isnull(contacts.companyphone,''))>0) and
(
companies.CompanyIntID = contacts.LinkToIntID) and
(
companies.CompanyPhone is null)
Go


xupdate companies
set companies.CompanyPhone = Contacts.DirectPhone
from
Contacts
where
(len(isnull(contacts.LinkToIntID,''))>0) and
(
len(isnull(contacts.DirectPhone,''))>0) and
(
companies.CompanyIntID = contacts.LinkToIntID) and
(
companies.CompanyPhone is null)
Go

53. cBizOne RegEdit Path

Sample Example:

Type "RegEdit" in Run and navigate to the following path

HKEY_CURRENT_USER
      - Software
           - VB and VBA Program Settings
               - xBar

54. SQL New Functions

COALESCE

SELECT COALESCE(NULL,'VISHNU','MURTHY') -- First non Nullable column
VISHNU --O/P

QUOTENAME

SELECT QUOTENAME('SQL Server Rider')
SELECT
QUOTENAME('SQL Server Rider', '''')
SELECT
QUOTENAME('SQL Server Rider', '"')
SELECT
QUOTENAME('SQL Server Rider', '<')

Out Put:
[SQL Server Rider]

'SQL Server Rider'

"SQL Server Rider"

<
SQL Server Rider>

------------------------------------------------------------
IF
(SELECT COUNT(*) FROM Links, Consultants, Contacts ) > 0
SELECT 'SUCCESS'
GO

-- Query cost 50%

IF
EXISTS (SELECT * FROM Links, Consultants, Contacts )
SELECT
'SUCCESS'
GO

-- Query cost 50%
------------------------------------------------------------

-- 10 MIN TO RUN THIS QUERY
-----------------------------

DECLARE
@aa INT

SELECT
@aa = 1

FROM
Consultants, links

SELECT
@aa
-----------------------------

 -----------------------------
--0 MIN TO RUN THIS QUERY
-----------------------------

DECLARE
@aa int

SELECT
@aa = 1

WHERE
EXISTS (SELECT 1 from Consultants, links)

SELECT
@aa
-----------------------------
------------------------------------------------------------

SET QUOTED_IDENTIFIER OFF
GO

EXECUTE
("SELECT 'Success' WHERE (1=1)")

SET
QUOTED_IDENTIFIER ON
GO

------------------------------------------------------------

How to use "SET QUOTED_IDENTIFIER OFF" in a Procedure

SET QUOTED_IDENTIFIER OFF

GO

CREATE PROCEDURE [dbo].[CBO_BulkMergeCandidatesOnPhone]
@NumberOfMergeRecords INT,
@TestPhoneNumber NVARCHAR(200) = ''
AS
BEGIN
SET NOCOUNT ON

DECLARE @MasterConsIntID NVARCHAR(10),
@SlaveConsIntID NVARCHAR(10)

.......

END

SET QUOTED_IDENTIFIER ON

GO

------------------------------------------------------------
-- Alter Table Schema

ALTER SCHEMA dbo TRANSFER cBiz_millstream.SaveSetInfo
go

------------------------------------------------------------

The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify. PATINDEX can use wildcard characters, but CHARINDEX cannot.

Example :

SELECT CHARINDEX('arm', 'vishnuarmmurthy') AS POSITION

SELECT PATINDEX('%reflector%', 'vishnu murthy reflector') AS POSITION

------------------------------------------------------------

55.Error while running the cBizOneHostingScript

ALTER TABLE Consultants ALTER COLUMN Summary [NTEXT];
-- Out Put
-- Error

SELECT
COUNT (*)
FROM
Consultants
WHERE
LEN( ISNULL( Summary,'')) = 0

UPDATE
Consultants SET Summary = NULL
WHERE
LEN (ISNULL (Summary,'')) = 0

ALTER
TABLE Consultants ALTER COLUMN Summary [NTEXT];
-- Out Put
-- Command(s) completed successfully.

56. LookUp is Pointing to wrong lookUp Values

Eg: Consultants "Status...", "Sub-Type" Lookup Point to "Reminders.ApptSubType,Status,Status,Contacts,Status,Status,Consultants" but it should point to "Reminders.ApptSubType,Status,Status,Consultants".

Even we change it to correct value still it is pointing to same.

Solution:

Replace the RemindersFields.xml from Sys Files.

57.
Bug in the cBizOne Users Table -
When we delete the users table group it will not delete the previously assigned users

DELETE Users
WHERE
(RecType = '1002') AND
(
SELECT COUNT(*)
FROM
Users U
WHERE
U. RecType = '1001' AND U. ID = Users .RPointer
)
= 0

58. Execute on all "cBiz_" Databases

--------------------------------------------------------------------------------------------------------------------

-- List All the Database's on the Server

SET
NOCOUNT ON
SET
QUOTED_IDENTIFIER OFF

DECLARE @SQL NVARCHAR(max)

SELECT
@SQL = "
use [?]
IF(('?' like 'cbiz[_]%') OR ('?' like 'exl[_]%'))
BEGIN
    PRINT '?'
END
"

EXEC
sp_MSforeachdb @SQL

SET
QUOTED_IDENTIFIER ON
SET
NOCOUNT OFF

 --------------------------------------------------------------------------------------------------------------------
-- Triggers on the Server
SET
NOCOUNT ON
SET
QUOTED_IDENTIFIER OFF

DECLARE
@SQL NVARCHAR(max)

SELECT
@SQL = "
use [?]
IF(('?' like 'cbiz[_]%') OR ('?' like 'exl[_]%'))
BEGIN
IF (
SELECT COUNT(*)
FROM sysobjects s1 JOIN sysobjects s2 ON s1.parent_obj = s2.[id]
WHERE s1.xtype = 'TR'
) > 0
PRINT '?'
END
"

EXEC
sp_MSforeachdb @SQL

SET
QUOTED_IDENTIFIER ON
SET
NOCOUNT OFF

--------------------------------------------------------------------------------------------------------------------
-- Audit Triggers on the Server

SET
NOCOUNT ON
SET
QUOTED_IDENTIFIER OFF
DECLARE
@SQL NVARCHAR(max)

SELECT
@SQL = "
use [?]
IF(('?' like 'cbiz[_]%') OR ('?' like 'exl[_]%'))
BEGIN
IF (
SELECT COUNT(*)
FROM sysobjects s1 JOIN sysobjects s2 ON s1.parent_obj = s2.[id]
WHERE s1.xtype = 'TR' AND
(s1.[name] LIKE '%Audit%')
) > 0
PRINT '?'
END
"

EXEC
sp_MSforeachdb @SQL

SET
QUOTED_IDENTIFIER ON
SET
NOCOUNT OFF

 
--------------------------------------------------------------------------------------------------------------------
-- Exemple 1
DECLARE
@Value1 NVARCHAR(200), @Value2 NVARCHAR(20), @SQL NVARCHAR(max)

SET
@Value1 = '"linkedin|'
SET
@Value2 = '",'
SELECT
@SQL = '
use [?]
IF((''?'' like ''cbiz[_]%'') OR (''?'' like ''exl[_]%''))
BEGIN
IF (
SELECT TOP 1 COUNT(*)
FROM Consultants
where (UserField5 LIKE ''linkedin,'')
) > 0
BEGIN
PRINT ''?''
update consultants set JobBoardIDs = '''
+ @Value1 + '''+userfield6+''' + @Value2 +''', uuSourceWebSites = UserField5
where DATALENGTH(isnull(userfield5,''''))>0 AND
DATALENGTH(isnull(userfield6,''''))>0 AND
(userfield5 LIKE ''linkedin,'')
END
END
'

EXEC
sp_MSforeachdb @SQL

59. Find which requirement have more Submissions

SELECT DISTINCT(Req) AS Req, SUM( XCount) as XCount
FROM

(

SELECT DISTINCT(ToID) AS Req , COUNT (*) as XCount
FROM MLinkInfo
WHERE (MLinkInfo.Type=1 AND MLinkInfo .SubType=1) AND (ToID like 'RQ%' )
GROUP BYToID

UNION ALL

SELECT DISTINCT(SentToIntID) AS Req, COUNT(*) as XCount
FROM EMailsSent
WHERE EMailsSent.MailType = 'Resume' AND (SentToIntID like 'RQ%')
GROUP BY SentToIntID
)
TEMP
GROUP
BY Req
ORDER
BY XCount DESC

-------------------------------------------------

SELECT [ItemIntID], XCount from
( SELECT [ItemIntID], Count(*) as XCount FROM [dbo].[Reminders]
where [ItemIntID] like 'RQ%' GROUP BY [ItemIntID] ) t
ORDER BY XCount DESC

60. Query will not build STATISTICS (IMP, Use this on Live Server)

DECLARE @Sql_Query NVARCHAR(MAX)
SET @Sql_Query ='SET QUOTED_IDENTIFIER OFF'
SELECT @Sql_Query +='
EXEC ("DROP STATISTICS ['
+ su.name + '].[' + so.name + '].[' + si.name + ']") '
FROM sysindexes si JOIN sysobjects so ON si.id = so.id JOIN sysusers su on su.uid = so.uid
WHERE INDEXPROPERTY(si.id,si.name, 'IsStatistics') = 1
--AND si.name not like '_WA_Sys%'

AND
OBJECTPROPERTY(so.id, 'IsUserTable') = 1
ORDER BY so.name, si.name
SET @Sql_Query +='
SET QUOTED_IDENTIFIER ON '

--Print @Sql_Query

EXEC(@Sql_Query)
Print 'Query Name: ABC'

ALTER DATABASE [Exl_VishnuTest1] SET AUTO_CREATE_STATISTICS OFF
GO
DECLARE
@StartDateTime DATETIME
SET
@StartDateTime = GETDATE()

----------------------------------------------------------------

-- Put your Query here

----------------------------------------------------------------

PRINT 'Time Took:' + CAST (DATEDIFF( MS,@StartDateTime ,GETDATE()) AS CHAR (100 ))
ALTER
DATABASE [Exl_VishnuTest1] SET AUTO_CREATE_STATISTICS ON
GO

60.1. Delete all User Table Statistics for a database

DECLARE @Sql_Query NVARCHAR(MAX )
SET
@Sql_Query ='SET QUOTED_IDENTIFIER OFF
'

SELECT
@Sql_Query +='EXEC ("DROP STATISTICS [' + su .name + '].[' + so .name + '].[' + si .name + ']")
'

FROM
sysindexes si
JOIN
sysobjects so
ON
si. id = so .id
JOIN
sysusers su
on
su. uid = so .uid
WHERE
INDEXPROPERTY(si .id, si.name , 'IsStatistics' ) = 1
--AND si.name not like '_WA_Sys%'

AND
OBJECTPROPERTY( so.id , 'IsUserTable' ) = 1
ORDER
BY so.name , si .name
SET
@Sql_Query +='SET QUOTED_IDENTIFIER ON
'

Print
@Sql_Query
EXEC
( @Sql_Query)

60.2. Analyzing & Optimizing T-SQL Query Performance

--DO NOT RUN THIS ON PRODUCTION!!!
DBCC
DROPCLEANBUFFERS;
DBCC
FREEPROCCACHE;
DBCC
FREESESSIONCACHE;
GO

SET
STATISTICS IO ON;
SET
STATISTICS TIME ON;
ALTER DATABASE [cBiz_test2] SET AUTO_CREATE_STATISTICS OFF;
GO

SELECT
COUNT(*) FROM Consultants
GO

ALTER DATABASE [cBiz_test2] SET AUTO_CREATE_STATISTICS ON;
SET
STATISTICS TIME OFF;
SET
STATISTICS IO OFF;
GO

Note: Use NOCOUNT ON Returns the single biggest performance boosts when coding stored procedures, triggers, and functions. Even casual scripting can experience a significant boost!

SET NOCOUNT ON < code > SET NOCOUNT OFF

60.2.1. SQL Server is not very good in optimizing the OR condition predicates.

Even though columns in the WHERE clauses are covered by indexes, SQL Server is unable to use these indexes. This raises the question as to whether anything is “blocking” the use of the indexes. The answer to this question is yes -- the culprits are the parameters and the “OR” condition.

Example: Performance Issue with OR Operator

Select
key3
From
Table
Where
(@key1 =0 OR Key1 =@Key1)

Solution: Use UNION ALL

SELECT
  key3
FROM
    Table
WHERE
   @key1 = 0

UNION
ALL

SELECT
  key3
FROM
    Table
WHERE
   @key1 <> 0 AND key1 = @key1

60.3. Clearing Cache for SQL Server Performance Testing (IMP Don't Use This on Live Server)

USE [1DemoDataBase]
GO
CHECKPOINT
;
GO

DBCC
DROPCLEANBUFFERS;
GO


SELECT
*
FROM
Contacts, Links, Requirements

Example:

----------------------------------------------------
CHECKPOINT
GO
DBCC
DROPCLEANBUFFERS
GO
SET
STATISTICS IO ON
GO
SET
STATISTICS TIME ON
GO
ALTER DATABASE [cBiz_test2] SET AUTO_CREATE_STATISTICS OFF
GO


EXEC
dbo .XCBO_UserActivitiesCountsReport '3/6/2000' ,'3/6/2013' ,'Kris|Admin|<Avg-Sel>|Ahmed|Alex|<Avg-All>|Bob|Bryan|Test' ,'Test'

ALTER DATABASE [cBiz_test2] SET AUTO_CREATE_STATISTICS ON
GO

SET
STATISTICS TIME OFF
GO
SET
STATISTICS IO OFF
GO

----------------------------------------------------

Link: http://www.mssqltips.com/sqlservertip/1360/clearing-cache-for-sql-server-performance-testing/

60.4. Using with clause(IMP)

The query against sys.dm_exec_query_stats is an efficient way to determine which query is using the most cumulative CPU.

select
DB_NAME(q .dbid) as DB_NAME , OBJECT_NAME(q .objectid, q.dbid ) as OBJECT_NAME , highest_cpu_queries .plan_handle, highest_cpu_queries .total_worker_time,
q
. number, q. encrypted, highest_cpu_queries .total_rows, highest_cpu_queries .creation_time, highest_cpu_queries .last_execution_time, q.[text]
from

(
select top 500 qs .plan_handle, qs .total_worker_time, qs .creation_time, qs .last_execution_time, qs .total_rows
from
sys.dm_exec_query_stats qs
order
by qs .total_worker_time desc) as highest_cpu_queries cross apply sys .dm_exec_sql_text( plan_handle) as q
order
by highest_cpu_queries.total_worker_time desc

60.5. Obtaining information about the top five queries by average CPU time(IMP)

SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],SUBSTRING(st.text, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2) + 1) AS statement_text FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER
BY total_worker_time/execution_count DESC;

60.6. Obtaining top 100 Query shoted to a pertical database(V.V.V.IMP)

SELECT TOP 100 DB_NAME(q.dbid) as DB_NAME, OBJECT_NAME(q.objectid,q.dbid) as OBJECT_NAME, qs.plan_handle, qs.total_worker_time,
q.number, q.encrypted, qs.total_rows, qs.creation_time, qs.last_execution_time, qs.total_worker_time, q.objectid, q.[text]

FROM
sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.plan_handle) as q  
WHERE
(DB_NAME(q.dbid) = 'cBizSoft') 
ORDER
BY qs.last_execution_time DESC  

61. Using with clause

The WITH keyword is used to create a temporary named result set, that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

WITH Administrators ( Name, Surname )
AS
(

SELECT Name, Surname FROM Users WHERE AccessRights = 'Admin'
)

SELECT
* FROM Administrators

61.1 How Recursive Common Table Expression (CTE) Works ?

Example1:

declare @StartDate smalldatetime, @Wk int, @pSchoolEndDate smalldatetime
set
@StartDate = '1/1/1900'
SET
@Wk = 1
set
@pSchoolEndDate = '1/1/2040'

;
with cte ([Date],Wk,DOW)
as
(
select
@StartDate,@Wk,datepart(dw,@StartDate)
union
all
select
[Date]+1,case when DOW=1 then Wk+1 else Wk end,datepart(dw,[Date]+1)
from
cte
where
[Date]<@pSchoolEndDate
)

select
*
from
cte
OPTION
(MAXRECURSION 0);

Note: 100 is the default limit for CTE, one can set it upto 32767 with 'maxrecursion'

Example2:

DECLARE @SplitList NVARCHAR( 4000);
SELECT
@SplitList = 'Count Howmany Characters InString' ;
WITH
Listings ( Position, CharacterSymbol ) AS
(

SELECT 1, SUBSTRING (@SplitList, 1, 1)
UNION ALL
SELECT Position + 1 , SUBSTRING (@SplitList,Position + 1, 1 )
FROM Listings
WHERE Position <= LEN( @SplitList) - 1
)

SELECT
CASE WHEN CharacterSymbol = '' THEN 'Empty Space' ELSE CharacterSymbol END AS WCharacter , COUNT(CharacterSymbol)
FROM
Listings
GROUP
BY CharacterSymbol
OPTION
(MAXRECURSION 0);

Example3:

WITH Number
AS (SELECT 1 AS n
UNION ALL
SELECT n + 1
FROM Number
WHERE n < 32767 )

SELECT
n
FROM
Number
OPTION
( MAXRECURSION 32767 );

Note:
The CTE usage has some disadvantages, one of them being the fact that CTE’s members cannot use the following clauses or keywords: DISTINCT, GROUP BY, HAVING, TOP, LEFT/RIGHT/OUTER JOIN, limiting by this the types of the queries that can be created and reducing their complexity. Other disadvantage can be the fact that the recursion is limited as the recursive member can refer to the CTE only once.

Attention:

Note: ContactsReceived is a With Table

Fast Query:
SELECT Consultants.ConsIntID,Consultants.DisplayName as Candidate,Consultants.JobTitle AS CandJobTitle,Requirements.ReqIntID,Requirements.ReqID,Requirements.JobTitle as ReqJobTitle,Requirements.Location, Contacts.ContactIntID,Contacts.DisplayName as Contact,Contacts.CompanyName as Company,Reminders.ApptSubType AS Stage, Reminders.Subject,Reminders.StartDateTime AS DateAndTime,dbo.XCBO_TrimDelimiter(Reminders.UserIDs) as UserIDs FROM dbo.GetReminderLinks('Status','Status',NULL) AS GetReminderLinks, RemindFROM dbo.GetReminderLinks('Status','Status',NULL) AS GetReminderLinks, Reminders, Consultants, Contacts, ContactsReceived, Requirements, RequirementsReceived
WHERE (Consultants.ConsIntID = GetReminderLinks.ConsIntID) AND (Contacts.ContactIntID = GetReminderLinks.ContactIntID) AND (Requirements.ReqIntID = GetReminderLinks.ReqIntID) AND (GetReminderLinks.ConsIntID = ContactsReceived.ConsIntID) AND (Reminders.RemIntID = GetReminderLinks.RemIntID) AND (ContactsReceived.ContactIntID = GetReminderLinks.ContactIntID) AND (RequirementsReceived.ReqIntID = GetReminderLinks.ReqIntID)

Time Taking Query:
SELECT Consultants.ConsIntID,Consultants.DisplayName as Candidate,Consultants.JobTitle AS CandJobTitle,Requirements.ReqIntID,Requirements.ReqID,Requirements.JobTitle as ReqJobTitle,Requirements.Location, Contacts.ContactIntID,Contacts.DisplayName as Contact,Contacts.CompanyName as Company,Reminders.ApptSubType AS Stage, Reminders.Subject,Reminders.StartDateTime AS DateAndTime,dbo.XCBO_TrimDelimiter(Reminders.UserIDs) as UserIDs Reminders, Consultants, Contacts, ContactsReceived, Requirements, RequirementsReceived FROM dbo.GetReminderLinks('Status','Status',NULL) AS GetReminderLinks, Reminders, Consultants, Contacts, ContactsReceived, Requirements, RequirementsReceived
WHERE (Consultants.ConsIntID = ContactsReceived.ConsIntID) AND (Contacts.ContactIntID = ContactsReceived.ContactIntID) AND (Requirements.ReqIntID = RequirementsReceived.ReqIntID) AND (GetReminderLinks.ConsIntID = ContactsReceived.ConsIntID) AND (Reminders.RemIntID = GetReminderLinks.RemIntID) AND (ContactsReceived.ContactIntID = GetReminderLinks.ContactIntID) AND (RequirementsReceived.ReqIntID = GetReminderLinks.ReqIntID) Fix for Exelare Bug in xTabs, views... (Eg. xTab is working in cBizOne but not working in Exelare)

UNION ALL

SELECT '','','','' ,'','',''
WHERE
(1= 2)

62. How to split a comma-separated value to columns

DECLARE @stringToSplit VARCHAR(MAX), @Split_Name NVARCHAR(255), @Split_Pos INT
DECLARE
@Comma_Split_List TABLE(Value VARCHAR(MAX))
SET
@stringToSplit = 'Vishnu, Ram, Water, Boost'
WHILE
CHARINDEX(',', @stringToSplit) > 0
BEGIN

      
SET @Split_Pos  = CHARINDEX(',', @stringToSplit) 
      
SET @Split_Name = SUBSTRING(@stringToSplit, 1, @Split_Pos-1)
      
INSERT INTO @Comma_Split_List SELECT LTRIM(RTRIM(@Split_Name))
      
SET @stringToSplit = SUBSTRING(@stringToSplit, @Split_Pos+1, LEN(@stringToSplit)-@Split_Pos)

END
INSERT
INTO @Comma_Split_List SELECT LTRIM(RTRIM(@stringToSplit))

SELECT
* FROM @Comma_Split_List 

63. Recently add Duplicate Candidates on Email1 View

WITH DuplicateConsultants
AS
(

SELECT ConsIntID, EMail1, CREATEDATE, ROW_NUMBER() OVER (PARTITION BY EMail1 ORDER BY CREATEDATE ASC) as DuplicateCount
FROM Consultants
WHERE LEN(ISNULL(EMAIL1,''))>0
)

SELECT *
FROM DuplicateConsultants
WHERE DuplicateCount > 1
ORDER BY EMail1, DuplicateCount

63.1. PARTITION Example:

SELECT DisplayName, CompanyName, ROW_NUMBER() OVER (PARTITION BY CompanyName ORDER BY DisplayName) AS theRow
FROM Contacts

64. Last Time a Table was Accessed

WITH LastActivity (TableName, DateAndTime, LastAction) AS
(
SELECT OBJECT_NAME(object_id) AS TableName,
last_user_seek
as DateAndTime, 'seek' AS LastAction
FROM sys.dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())

UNION

SELECT OBJECT_NAME(object_id) AS TableName,
last_user_scan
as DateAndTime, 'scan' AS LastAction
FROM sys .dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())

UNION

SELECT OBJECT_NAME(object_id) AS TableName,
last_user_lookup
as DateAndTime, 'lookup' AS LastAction
FROM sys .dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())
)

SELECT TableName, MAX (DateAndTime) AS DateAndTime, LastAction
FROM
LastActivity
GROUP
BY TableName , LastAction
ORDER
BYTableName

65. IMP

1. You can not compare 'NULL' Values Like This

SELECT 'asdasd'
WHERE (null = null)

66. Delete large amount of data in sql server

DECLARE
@RowsDeleted INTEGER
SET
@RowsDeleted = 1

WHILE
(@RowsDeleted > 0)
BEGIN
      
DELETE TOP (10000) FROM MyTable [WHERE .....] -- WHERE is optional
      
SET @RowsDeleted = @@ROWCOUNT
END

67. Issue in Trigger Using IF UPDATE()
When we have AuditTrigger and Insert, Update Trigger the IF UPDATE() will give issues.

IF UPDATE(City)
BEGIN
    .....
END

Solution:
IF (
SELECT COUNT(*)
FROM INSERTED LEFT JOIN DELETED ON (INSERTED.[ConsIntID] = DELETED.[ConsIntID])
WHERE (ISNULL(INSERTED.City,'') != ISNULL(DELETED.City,''))
) > 0
BEGIN
   ....
END

67.1. Issue in Trigger Using IF UPDATE() IN EXELARE (Found for xUsers in cBizSoft DB)

--NOTE: For Some reason, if updating raising even data not changed (May be Date and Smalldatetime issues)

DECLARE @ExpiryDate_Changed INT , @Status_Changed INT

SELECT
@ExpiryDate_Changed = COUNT (1 )
FROM
INSERTED LEFT JOIN DELETED ON ( INSERTED.[CompanyID] = DELETED .[CompanyID] AND INSERTED.[UserID] = DELETED .[UserID])
WHERE ( ISNULL(INSERTED .ExpiryDate, '1/1/1900') != ISNULL (DELETED. ExpiryDate,'1/1/1900' ))

SELECT @Status_Changed = COUNT(1)
FROM
INSERTED LEFT JOIN DELETED ON (INSERTED.[CompanyID] = DELETED.[CompanyID] AND INSERTED.[UserID] = DELETED.[UserID])
WHERE (ISNULL(INSERTED.Status,'') != ISNULL(DELETED.Status,''))

IF (@ExpiryDate_Changed>0 OR @Status_Changed>0)
BEGIN

.........

END

68. Sample Query to find the Duplicate records on Requirement - Status On Requirement (IMP)

DECLARE @Count INT, @TotalCount INT, @ItemIntID_T NVARCHAR(10), @Subject_T NVARCHAR(300)

SELECT [ItemIntID], [Subject], IDENTITY( int ) AS idcol INTO #newtable from [Reminders] where subject like 'Job Status:%' group by [ItemIntID], [Subject] having count(*)>1

SELECT @TotalCount = COUNT(*) FROM #newtable
SET @Count = 1
WHILE(@Count <= @TotalCount)
BEGIN
SELECT @ItemIntID_T = ItemIntID, @Subject_T = SubjecT FROM #newtable WHERE idcol = @Count

SELECT * FROM reminders WHERE (ItemIntID = @ItemIntID_T) AND (Subject = @Subject_T) and reminders.RemIntID != ( select top 1 r.RemIntID from reminders r WHERE (r.ItemIntID = @ItemIntID_T) AND (r.Subject = @Subject_T) order by r.CreateDate asc )
SET @Count = @Count + 1
END
DROP TABLE #newtable

69. Explanation of Regular Expressions:

Regular expressions are used to search specified in the source string.

Examples:
Pattern#1 Regex objNotNaturalPattern=new Regex("[^0-9]");
Pattern#2 Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");

Pattern#1 will match for strings other than 0 to 9.^ symbol is used for Specifying not condition.[] brackets if we are to give range values such as 0 - 9 or a-z or A-Z eg. abc will return true 123 will return false.

Pattern#2 will match for string which are Natural Numbers.Natural numbers Are numbers which are always greater than 0.The pattern 0* tells that a natural Number can be prefixed with any number of zero's or no zero's.the next [1-9] tells that it should contain atleast one number from 1 to 9 followed by any numbers of 0-9's Eg. 0007 returns true whereas 00 will return false.

Basic things to be understood in RegEx: "*" matches 0 or more patterns "?" matches single character "^" for ignoring matches. "[]" for searching range patterns.

Help Like's:
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
http://www.c-sharpcorner.com/UploadFile/prasad_1/RegExpPSD12062005021717AM/RegExpPSD.aspx

70. How To Copy SQL Server 2005 Jobs From One Server To Another:

Right-click on the job that you want to copy over to a second server.
Select Script Job as –> Create To –> New Query Editor Window.

Link: http://robbamforth.wordpress.com/2009/05/01/how-to-copy-sql-server-2005-jobs-from-one-server-to-another/

71. Convert Rows to Columns:

SELECT ColumnName, DataValue
FROM
(
SELECT Exl_Licenses, cBiz_Licenses, Digits16_Licenses, ThinClient FROM [dbo].[PadmacBizSoftLicenseCount] WHERE (LicenseCountDate > DATEADD(DAY,-2,GETDATE()))
) MainTable
UNPIVOT
(DataValue FOR ColumnName IN (Exl_Licenses, cBiz_Licenses, Digits16_Licenses, ThinClient)
) AS TempTable
 

72. Differences between ISNULL and COALESCE:

Both ISNULL and COALESCE can be used to get the same results but there are some differences.
1. Data type determination of the resulting expression - ISNULL uses the first parameter type, COALESCE follows the CASE expression rules and returns type of value with highest precedence
2. ISNULL(NULL, NULL) -- is int
COALESCE(NULL, NULL) -- Will throw an error
COALESCE(CAST(NULL as int), NULL) -- it valid and returns int
3. ISNULL takes only 2 parameters whereas COALESCE takes variable number of parameters
select COALESCE('SSS',NULL,'DD', 'eee')
select COALESCE(NULL,NULL,NULL, 'eee')
4.This will make a performance difference and queries with COALESCE often fare worse here.

73. Round to one Decimal Point:

SELECT CONVERT(decimal(18, 1), ROUND(0.857142895460129, 1)) as GoalValue

74. No More Multiple UserID's (Single UserID):

SELECT XCount,What,UserIDsSingle as UserIDs
FROM
(
 SELECT count(*) as XCount,UserIDs,max('Companies') as What
 FROM Companies
 GROUP BY UserIDs
) MultipeUsers LEFT JOIN
(SELECT UserIDsSingle FROM (SELECT ','+ID+',' AS UserIDsSingle,0 Private FROM Users WHERE RecType='20') SingleUsers1
) SingleUsers
ON MultipeUsers.UserIDs LIKE '%'+SingleUsers.UserIDsSingle+'%'

74. Convert Requirements.NumberOfOpenings to INT

DECLARE @ObjectName NVARCHAR(100)
SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID('Requirements') AND [name] = 'NumberOfOpenings';
EXEC('ALTER TABLE Requirements DROP CONSTRAINT ' + @ObjectName)

ALTER TABLE Requirements
ALTER COLUMN NumberOfOpenings INT

75. Avoid SQL Server functions in the WHERE clause for Performance

Execute Slow:
SELECT EmailAddress
FROM person.contact
WHERE left(EmailAddress,2) = 'As'

Execute Fast: (SQL Server can do an index seek which is much more efficient then an index scan)
SELECT EmailAddress
FROM person.contact
WHERE EmailAddress like 'As%'

Help Link:
 
http://www.databasejournal.com/features/mssql/article.php/3845381/T-SQL-Best-Practices-150-Don146t-Use-Scalar-Value-Functions-in-Column-List-or-WHERE-Clauses.htm
http://www.mssqltips.com/sqlservertip/1236/avoid-sql-server-functions-in-the-where-clause-for-performance/
http://www.blog.namwarrizvi.com/?p=101

76. The SQL LIKE operator very often causes unexpected performance behaviour

Tip Avoid LIKE expressions with leading wildcards (e.g., '%TERM').

SELECT ES.UserIDs, COUNT(*) AS NoContacted
FROM [EMailsSent] ES
WHERE (ES.EMail
= CTDBECM.EMail)
GROUP BY ES.UserIDs

Out Put: 3 Min

SELECT ES.UserIDs, COUNT(*) AS NoContacted
FROM [EMailsSent] ES
WHERE (ES.EMail
like '%' + CTDBECM.EMailDomain)
GROUP BY ES.UserIDs

Out Put: 2 Hr

Solution:
   
Use the FullText Catalog

SELECT ES.UserIDs, COUNT(*) AS NoContacted
FROM [EMailsSent] ES
WHERE (
CONTAINS(ES.EMail, @EMailDomain))
GROUP BY ES.UserIDs

Out Put: 18 Min

Example Function: CBO_GetEmailSendUserIDsandCounts (From the Email Domain get the EmailSend UserID's and Counts)(Insted of Using Like Operater using the Fulltext Catalog)

77. Use sp_settriggerorder stored procedure to change trigger firing order.

Examples:
exec sp_settriggerorder @triggername = 'CBO_AppendDoller',
@order = 'LAST',
@stmttype = 'insert'

exec sp_settriggerorder @triggername = 'CBO_TriggerOrderDemo',
@order = 'first',
@stmttype = 'insert'

exec sp_settriggerorder @triggername = 'CBO_AppendDoller',
@order = 'none',
@stmttype = 'insert'

exec sp_settriggerorder @triggername = 'CBO_TriggerOrderDemo',
@order = 'none',
@stmttype = 'insert'

78. Debug SQL Query in Management Studio(F11).

Examples:
CREATE PROCEDURE Perfect (@Input INT)
AS
DECLARE
@temp INT = 1,
@counter INT = 2;
BEGIN
IF(@Input < 1)
BEGIN
RAISERROR('Enter a positive number',16,1)
return;
END

Start Debug Mode:
WHILE(@counter <= @Input/2)
BEGIN
IF(@Input % @counter = 0)
BEGIN
SET @temp = @temp + @counter
END
SET @counter = @counter + 1
END
IF(@temp = @Input)
BEGIN
PRINT 'Perfect Number ' + CAST( @Input AS NVARCHAR )
END
ELSE
BEGIN
PRINT 'Not Perfect ' + CAST( @Input AS NVARCHAR )
END
END
EXEC Perfect 6

79. Insert Large Amount of Data in to Database(Bulk Insert).

Examples 1:
BULK
INSERT ZipCodes
FROM
'C:\Users\Vishnu.Vishnu\Desktop\NewDatabaseScript\ZipCodes.CSV'
WITH

(

FIELDTERMINATOR
= ',',
ROWTERMINATOR
= '\n'
)

Examples 2:
CREATE TABLE [dbo].[Stickers] (
[name] varchar(10)

,
[category] varchar(10)
,
[gender] varchar(1)
,
[imageData] varchar(max)
)


INSERT
INTO  [dbo].[Stickers] ([name], [category], [gender], [imageData])
SELECT
'Red dress'
       
, 'Dress'
       
, 'F'
       
, photo.*

FROM
OPENROWSET(BULK 'D:\20150707_150530.jpg', SINGLE_BLOB) [photo]

Note: LogInID - Server Roles - Select bulkadmin to be able to use bulk commands or sysadmin to be able to use any commands to your database.

80. Create New Table With Select Command/With Existing Tables.

SELECT *
INTO
Companies1
FROM
Companies
WHERE
(1= 1)

81. Generating Integer Random Number in given Limits .

---- Create the variables for the random number generation

DECLARE @Random INT;
DECLARE
@Upper INT;
DECLARE @Lower INT

SET @Lower = 1
SET
@Upper = 999
SELECT
@Random = ROUND (((@Upper - @Lower -1) * RAND () + @Lower ), 0 )
SELECT
@Random

82. SQL Server update trigger is not working(GET SINGLE RECORD AT A TIME)(IMP).

False assumption that it will execute once per row. It doesn't, it executes once per action - so when you update the entire table, I bet if you look closer, you'll see that one row was updated.

Solution:

SET NOCOUNT ON;
DECLARE
@TotalCount BIGINT, @Count BIGINT
SELECT
ReqIntID, VisaStatus , IDENTITY( int ) AS idcol INTO #newtable
FROM
[dbo]. [RemoveVISHNU]

SELECT @TotalCount = COUNT(*)
FROM
#newtable

SET @Count =1

WHILE (@Count <= @TotalCount )
BEGIN
UPDATE Requirements SET Requirements .VisaStatus = #newtable.VisaStatus
FROM #newtable
WHERE (#newtable. idcol = @Count ) AND (Requirements. ReqIntID = #newtable .ReqIntID)

SET @Count += 1
END

PRINT '(' + CAST (@Count AS CHAR(5)) + ' row(s) affected)'
DROP
TABLE #newtable

82.1. Get Single Record and Update One After Other in a Loop(With Out Using Cursor)

SET NOCOUNT ON;
DECLARE
@Count INT, @TotalCount INT, @Domain_T NVARCHAR(MAX)

SELECT
Domain, IDENTITY( int ) AS idcol INTO #EmailDomain
FROM

(

      
SELECT DISTINCT(SUBSTRING(Email1, PATINDEX('%@%',Email1)+1,LEN(Email1))) as Domain
      
FROM [dbo].[Contacts]
      
WHERE LEN(ISNULL(Email1,''))>0 and Email1 like '%@%' and Email1 not like '@%'

)
TEMP

SELECT
@TotalCount = COUNT(*) FROM #EmailDomain
SET
@Count = 1

WHILE
(@Count <= @TotalCount)
BEGIN

      
SELECT @Domain_T = Domain FROM #EmailDomain WHERE idcol = @Count
      
IF((SELECT COUNT(1) FROM [dbo].[ContactsVerify] WHERE [Website] = @Domain_T) = 1)
      
BEGIN
             
UPDATE [dbo].[Contacts] SET uuEmailDomainExist = 1 WHERE Email1 LIKE '%@'+@Domain_T
             
DELETE [dbo].[ContactsVerify] WHERE [Website] = @Domain_T
      
END
      
SET @Count = @Count + 1

END

DROP
TABLE #EmailDomain  

OR

SET NOCOUNT ON;
DECLARE
@Count INT, @TotalCount INT, @ID NVARCHAR(512)
DECLARE @All_UserIDs TABLE ( IDx INT IDENTITY(1,1), Data NVARCHAR(512) )

INSERT
INTO @All_UserIDs (Data)
SELECT
ID FROM Users WHERE RecType = '20'; 
SELECT
@TotalCount = COUNT(*) FROM @All_UserIDs
SET
@Count = 1


WHILE(@Count <= @TotalCount)
BEGIN

      
SELECT @ID = Data FROM @All_UserIDs WHERE IDx = @Count
      
  
--Allow Sending SMS Messages
EXEC
dbo.XCBO_SaveUsersPermissions @ID,0,21,1,',<Self>,'
      
SET @Count = @Count + 1
END

83="2">. TRUNCATE TABLE

Less transaction log space is used, Fewer locks are typically used and Without exception, zero pages are left in the table.

TRUNCATE TABLE [dbo]. [ZipCodes]

83.1. TRUNCATE Documents TABLE leave Customizations

SELECT * INTO Documents_Temp FROM Documents WHERE ItemIntID LIKE 'CF%'
TRUNCATE
TABLE Documents
INSERT
INTO Documents SELECT * FROM Documents_Temp
DROP
TABLE Documents_Temp 

84. Copy DataFrom XML to TSQL Table

Sample XML File

Copy the above Sample file to D:\ Drive

DECLARE @xmlData XML
SET
@xmlData = (
SELECT * FROM OPENROWSET (
BULK 'D:\VishnuSampleXMP.xml' , SINGLE_CLOB
) AS xmlData
)

SELECT
ref .value( 'FilterID[1]', 'int') AS FilterID ,
ref.value ('Name[1]', 'NVARCHAR (10)') AS Name ,
ref.value ('Code[1]', 'NVARCHAR (10)') AS Code ,
ref.value ('Department[1]', 'NVARCHAR (3)') AS Department ,
ref.value ('Number[1]', 'int') AS Number
FROM
@xmlData. nodes('/ArrayOfSpangemansFilter/SpangemansFilter' )
xmlData
( ref )

85. Display Distinct values with minimum date (We Use this for First Submissions of a Candidate for a Requirement) (V.V.V.IMP)

select distinct dd, min (Date1) as Date1
from
(
select 'A' as dd , 1 as Date1
union
all
select
'A' as dd, 2 as Date1
union
all
select
'B' as dd, 1 as Date1
union
all
select
'A' as dd, 1 as Date1|
union
all
select
'B' as dd, 2 as Date1
)
tt
group
by dd

86. Display all the Values in the Order of minimum date  as 1 and so on (E.g.: Numbering the Duplicate Submissions) (V.V.V.IMP)

SELECT dd, Date1 , ROW_NUMBER() OVER (PARTITION BY dd ORDER BY dd , Date1) AS 'RowNumber'
from

(
select 'A' as dd , 1 as Date1
union
all
select
'A' as dd, 2 as Date1
union
all
select
'B' as dd, 1 as Date1
union
all
select
'A' as dd, 1 as Date1
union
all
select
'B' as dd, 2 as Date1
)
tt

OutPut:
Value1 Date1 RowNumber
A           1           1
A           1           2
A           2           3
B           1           1
B           2           2

86.1 Difference between ROW_NUMBER, RANK, DENSE_RANK, NTILE (V.V.V.IMP)

-- create table
CREATE
TABLE dbo. Grades
(
Names VARCHAR (1 ),Grade INT)
GO

-- insert data

INSERT
INTO dbo.Grades
VALUES
('A', 100),( 'B',90),('C' ,80 ),('D', 70),( 'E',70),('F' ,60 )
GO

-- Test the data
SELECT
Names, Grade,
ROW_NUMBER () OVER ( ORDER BY Grade DESC ) as ROW_NUMBER ,
RANK () OVER (ORDER BY Grade DESC ) as RANK,
DENSE_RANK () OVER (ORDER BY Grade DESC ) as DENSE_RANK ,
NTILE(3 ) OVER(ORDER BY Grade desc ) AS NTILE
FROM
dbo. Grades

Names Grade ROW_NUMBER RANK DENSE_RANK NTILE
----- ----------- -------------------- -------------------- --------------------
A         100                 1                                  1                1
       90                                  2                   2                1
C         80                   3                 3                   3                2
D         70                   4                 4                   4                2
E         70                   5                 4                   4                3
F         60                   6                                  5                3

Note: You can use "PARTITION BY" if you want to Group them.

86.2 SQL Find difference between previous and current row (V.V.V.IMP)

Status   columnOfNumbers
Vishnu              1
Vishnu              2
Vishnu              3
Vishnu              5
Vishnu              6
Vishnu              9
Ram                 1
Ram                 5
Ram                 7

WITH CTE AS (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY Status, columnOfNumbers) as ROW,Status, columnOfNumbers FROM vishnu_tableName)

SELECT
a.Status, a.columnOfNumbers, (a.columnOfNumbers - b.columnOfNumbers) as Diff
FROM
CTE a LEFT JOIN CTE b ON (a.ROW = b.ROW + 1 AND a.Status = b.Status)

OutPut:

Status   columnOfNumbers         Diff
Ram                   1                          NULL
Ram                   5                          4
Ram                   7                          2
Vishnu                1                          NULL
Vishnu                2                          1
Vishnu                3                          1
Vishnu                5                          2
Vishnu                6                          1
Vishnu                9                          3

Example:
WITH CTE
AS

(

      
SELECT ROW_NUMBER() OVER (ORDER BY DateAndTime) as ROW, ApptSubType, DateAndTime
      
FROM

      
(
             
SELECT 'Filled' as ApptSubType, CAST('2016-05-04' AS DATETIME) as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2016-04-04' as DateAndTime
             
UNION ALL
             
SELECT 'DDD' as ApptSubType, '2016-03-04' as DateAndTime
             
UNION ALL
             
SELECT 'Active' as ApptSubType, '2016-02-04' as DateAndTime
             
UNION ALL
             
SELECT 'Filled' as ApptSubType, '2016-01-04' as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2015-12-04' as DateAndTime
             
UNION ALL
             
SELECT 'CCCC' as ApptSubType, '2015-11-04' as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2015-10-04' as DateAndTime
             
UNION ALL
             
SELECT 'Active' as ApptSubType, '2015-09-04' as DateAndTime
             
UNION ALL
             
SELECT 'RRRR' as ApptSubType, '2015-08-04' as DateAndTime
             
UNION ALL
             
SELECT 'Active' as ApptSubType, '2015-07-04' as DateAndTime
             
UNION ALL
             
SELECT 'BBBB' as ApptSubType, '2015-06-04' as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2015-05-14' as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2015-05-04' as DateAndTime
             
UNION ALL
             
SELECT 'Hold' as ApptSubType, '2015-04-04' as DateAndTime
             
UNION ALL
             
SELECT 'Active' as ApptSubType, '2015-03-04' as DateAndTime
             
UNION ALL
             
SELECT 'Active' as ApptSubType, '2015-02-04' as DateAndTime
             
UNION ALL
             
SELECT 'AAAA' as ApptSubType, '2015-01-04' as DateAndTime
      
) TEMP
      
WHERE  ApptSubType IN ('Active','Hold','Filled')

)


SELECT
ApptSubType, DateAndTime
FROM

(

      
SELECT a.ApptSubType, a.DateAndTime, (a.DateAndTime - b.DateAndTime) as Diff
      
FROM CTE a LEFT JOIN CTE b ON (a.ROW = b.ROW + 1 AND a.ApptSubType = b.ApptSubType)

)
TEMP
WHERE
Diff IS NULL

  7. Percentage Calculation(RAM)

CREATE FUNCTION CBO_Percent( @Input1 int , @Input2 int) returns decimal (10 ,2 )
AS
BEGIN
RETURN
CAST(( ISNULL((@Input1 *1.0 )/NULLIF( @Input2,0),0 ) * 100) as decimal (10 ,2 ))
END

88. cBizOne Customizations, StylSheets, Exelare Customizations and JobPages Info laded in Documents table

CF00000000 - cBiz Customize.zip
CF00000001 - Stylesheets.zip
CF90000000 - Exelare Customize.zip
JC00000003 - Job Pages
AS00000003 - Auto Schedule

89. Giving the permission to read the TSQL System Tables

Eg: GRANT VIEW SERVER STATE TO [cBiz_bentley] ;

Help Link: http: //dba. stackexchange.com /questions/ 34612/ give-permission -to- select-from -system- tables

89.1. Create LogIn User and give Permission to some Tables and all Procedure and Functions

USE [Exl_JDISearch]
GO
CREATE
LOGIN [Exl_JDISearch_User1] WITH PASSWORD='2led_45965'
CREATE USER [Exl_JDISearch_User1] FOR LOGIN [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[Companies] TO [Exl_JDISearch_User1]
GRANT
INSERT ON [dbo].[Companies] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Companies] TO [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[Contacts] TO [Exl_JDISearch_User1]
GRANT
INSERT ON [dbo].[Contacts] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Contacts] TO [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[Consultants] TO [Exl_JDISearch_User1]
GRANT
INSERT ON [dbo].[Consultants] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Consultants] TO [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[Counters] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Counters] TO [Exl_JDISearch_User1]
GRANT
SELECT ON [dbo].[Links] TO [Exl_JDISearch_User1]

GRANT
INSERT ON [dbo].[Links] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Links] TO [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[MLinkInfo] TO [Exl_JDISearch_User1]
GRANT
INSERT ON [dbo].[MLinkInfo] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[MLinkInfo] TO [Exl_JDISearch_User1]

GRANT
SELECT ON [dbo].[Reminders] TO [Exl_JDISearch_User1]
GRANT
INSERT ON [dbo].[Reminders] TO [Exl_JDISearch_User1]
GRANT
UPDATE ON [dbo].[Reminders] TO [Exl_JDISearch_User1]

GRANT
CREATE PROCEDURE TO [Exl_JDISearch_User1]
GRANT
CREATE FUNCTION TO [Exl_JDISearch_User1]

GRANT SELECT ON SCHEMA::[dbo] TO [Exl_JDISearch_User1]

GRANT
ALTER ON SCHEMA::[dbo] TO [Exl_JDISearch_User1]
GRANT
EXECUTE ON SCHEMA::[dbo] TO [Exl_JDISearch_User1] 

89.2. Create LogIn User and give Permission to ALL Tables, Views, Procedure and Functions

USE [Exl_VishnuTest1]
GO
CREATE
LOGIN [Exl_VishnuTest1] WITH PASSWORD='bfa44584e0'
CREATE
USER [Exl_VishnuTest1] FOR LOGIN [Exl_VishnuTest1]
------------------------------------------------------------

SELECT
'GRANT SELECT ON [dbo].[' + Table_Name + '] TO [Exl_VishnuTest1]'
FROM
INFORMATION_SCHEMA.TABLES

SELECT
'GRANT INSERT ON [dbo].[' + Table_Name + '] TO [Exl_VishnuTest1]'
FROM
INFORMATION_SCHEMA.TABLES

SELECT
'GRANT UPDATE ON [dbo].[' + Table_Name + '] TO [Exl_VishnuTest1]'
FROM
INFORMATION_SCHEMA.TABLES

SELECT
'GRANT DELETE ON [dbo].[' + Table_Name + '] TO [Exl_VishnuTest1]'
FROM
INFORMATION_SCHEMA.TABLES
------------------------------------------------------------

GRANT
CREATE PROCEDURE TO [Exl_VishnuTest1]
GRANT
CREATE FUNCTION TO [Exl_VishnuTest1]

GRANT
ALTER ON SCHEMA::[dbo] TO [Exl_VishnuTest1]
GRANT
EXECUTE ON SCHEMA::[dbo] TO [Exl_VishnuTest1]
GRANT
SELECT ON SCHEMA::[dbo] TO [Exl_JDISearch_User1]  

90. Handling only Single Insert/Delete in the Update Trigger (Not for BulkUpdates)(IMP IMP IMP)

CREATE TRIGGER [dbo]. [CBO_U_TEST]
ON [dbo] .[Consultants]
FOR UPDATE
AS

BEGIN
SET
NOCOUNT ON;
IF((SELECT COUNT (*) FROM INSERTED )=1 )
BEGIN
IF
UPDATE( [UserField1])
BEGIN
UPDATE [dbo] .[Consultants] SET [UserField2] = CAST ((SELECT COUNT(*) FROM INSERTED) AS NVARCHAR(10))
WHERE [ConsIntID] = 'CS00000106'
END
END
END

Note: Use this IF(( SELECT COUNT(*) FROM INSERTED)=1)Every time in the Trigger

91. Clean Cache and Clean Buffer (Don't USE this, IMP IMP IMP)

Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache. If observing through SQL Profiler, one can watch the Cache Remove events occur as DBCC FREEPROCCACHE goes to work. DBCC FREEPROCCACHE will invalidate all stored procedure plans that the optimizer has cached in memory and force SQL Server to compile new plans the next time those procedures are run.

Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. DBCC DROPCLEANBUFFERS serves to empty the data cache. Any data loaded into the buffer cache due to the prior execution of a query is removed.

DBCC FREEPROCCACHE
DBCC
DROPCLEANBUFFERS

Warning: These scripts should almost never be run on a production system. These are meant for debugging and testing on DEV. If you do run these on PROD, be sure to understand the consequences.

As with clearing the entire cache, this is probably not something you want to do with a production system unless you have a good reason. You may have one database that is a special case, which needs to be tamed.

Like a broken record, I got to remind you that it is a bad idea to do this on a production system.

How ever with out using this, upon executing a query and returning the results to the user, it stored the data in its buffer pool for a little while. If you rerun the query, Sql Server will be able to quickly return the results from memory rather than going to disk again. This is much faster. But every few minutes, this buffer pool is automatically cleared.

http://sqlavenger.wordpress.com/2011/05/23/clearing-the-plan-cache/

92. QUOTENAME Function

SELECT QUOTENAME ('Syntax-Example', '"')
Output:
"Syntax-Example"

SELECT  QUOTENAME('Syntax-Example' ,'''')
Output:
'Syntax-Example'

SELECT QUOTENAME( 'Syntax-Example')
Output:
[Syntax-Example]

93. How to catch the Dynamic SQL return Value (Execute sp_executesql with return parameters)

Example1:

DECLARE @TempColumn nvarchar (100 ) = 'UserIDs' , @IDS nvarchar( 100), @SQLQuery NVARCHAR (MAX)

SET @SQLQuery = 'SELECT @TempIDs =' + @TempColumn + ' FROM Companies
WHERE ( CompanyIntID = ''CM00000004'' ) AND (LEN(ISNULL( '
+ @TempColumn + ', ''''))>0)'

EXECUTE SP_EXECUTESQL @SQLQuery , N'@TempIDs nvarchar(100) OUTPUT' , @TempIDs = @IDs OUTPUT

Example2:

DECLARE @DynamicSQLOutPut TABLE(Value NVARCHAR(MAX))
DECLARE
@Query NVARCHAR(MAX)
SET
@Query=' 
SELECT 2222'


INSERT
INTO @DynamicSQLOutPut
EXEC
(@Query)

SELECT
* FROM @DynamicSQLOutPut 

Example3:

--- Drop global temp table
IF
OBJECT_ID('tempdb..##GlobalTempTable_Consultants','u') IS NOT NULL
DROP
TABLE ##GlobalTempTable_Consultants

DECLARE
@SQL_Query NVARCHAR(MAX)
SET
@SQL_Query = 'SELECT TOP 10 * INTO ##GlobalTempTable_Consultants FROM Consultants'
EXEC
(@SQL_Query)
SELECT
* FROM ##GlobalTempTable_Consultants

94. ISNUMERIC Check for Real only

IsNumeric would be the obvious choice, but has some problems because it allows for unexpected characters during the conversion. For example, the following strings will return true from the IsNumeric function.

$12.09
1.4e3
2d4

If you want to allow fractional numbers, then you can add e0 to the isnumeric test.

Select IsNumeric('$12.09' + 'e0')
Select
IsNumeric('1.4e3' + 'e0')
Select
IsNumeric('2d4' + 'e0')
Select
IsNumeric('3.7' + 'e0')

94.1. ISNUMERIC Check for INT only

SELECT ConsIntID, CAST(uuTemp AS INT), uuTemp
FROM
Consultants
WHERE
LEN(uuTemp) = 4 AND ISNUMERIC(uuTemp+'.e0') = 1

94.2. How to Use Regular expression in sql query(Eg. Get Decimal Value from String Number)

SELECT ConsIntID, CAST(uuTemp AS INT), uuTemp
FROM
Consultants
WHERE
LEN(uuTemp) = 4
AND
SubString(uuTemp,1,1) LIKE '[1-9]'
AND
SubString(uuTemp,2,1) LIKE '[1-9]'
AND
SubString(uuTemp,3,1) LIKE '[1-9]'
AND
SubString(uuTemp,4,1) LIKE '[1-9]'

95. How to print the messages while Query is running(NOWAIT)

Prints get buffered, releasing "chunks" as the buffer fills up.
So use RAISERROR with serverity 0 and the NOWAIT option

DECLARE @PRINTMessage NVARCHAR(1000)
SET
@PRINTMessage = CAST(@T_Count AS NVARCHAR (100 )) + ') ' + REPLACE (@T_ColumnName, '%','' ) + ' - Done'
RAISERROR(@PRINTMessage ,0 ,1 ) WITH NOWAIT

Note: Message can not have '%', it will think it as string format. So replace '%' with '' if you have.
NOWAIT will return error if the original table has (transaction) locked on it.
NOLOCK will read the data irrespective of the (transaction) lock on it.

OR

WHILE EXISTS (SELECT 1 FROM [dbo].[Consultants] WHERE uuResumeText_Clean = 0)
BEGIN

      
UPDATE TOP(1000) Consultants SET uuResumeText = dbo.CBO_CleanResumeText(uuResumeText), uuResumeText_Clean = 1
      
WHERE uuResumeText_Clean = 0
      
RAISERROR('Processed 1000 rows', 0, 1) WITH NOWAIT;
END

96. Checking Available Drive Space from within SQL Server(Free Disk Space)

CREATE TABLE #drives (drive char, [free] int)

INSERT INTO #drives
EXEC
master..xp_fixeddrives

SELECT drive, RTRIM (CONVERT( CHAR(50),([free] /1024.0 ))) + ' GB' AS FreeSpaceInGB
FROM
#drives

DROP TABLE #drives

SQL Server 2008 R2 SP1 and above:

SELECT DISTINCT dovs. volume_mount_point + ' ' + RTRIM (CONVERT( CHAR(50),CONVERT (REAL, dovs.available_bytes /1073741824.0 ))) + ' GB' AS FreeSpaceInGB
FROM
sys. master_files mf
CROSS
APPLY sys.dm_os_volume_stats (mf. database_id, mf.FILE_ID ) dovs

97. Using Try and Catch and ROLLBACK TRANSACTION(IMP)

BEGIN TRANSACTION
BEGIN TRY
SET QUOTED_IDENTIFIER OFF
SET XACT_ABORT ON
-- When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.

-- This will help insufficient disk space erroe
 
-- some query here.
 
COMMIT TRANSACTION
SET QUOTED_IDENTIFIER ON
END TRY
BEGIN CATCH        
   
ROLLBACK TRANSACTION
       
    DECLARE
@Msg NVARCHAR(MAX)         
    SELECT
@Msg=ERROR_MESSAGE()        
   
RAISERROR('Error Occured: %s', 20, 101,@msg) WITH LOG

END CATCH

98. Output results to text file using T-SQL(IMP)

DECLARE @OutputFile NVARCHAR(100), @FilePath NVARCHAR(100), @bcpCommand NVARCHAR(4000)
DECLARE
@SQL NVARCHAR(MAX) = 'SELECT * FROM sys.objects'

SET
@bcpCommand = 'bcp "'+ @SQL +' " queryout '
SET
@FilePath = 'D:'
SET
@OutputFile = 'FileName1.txt'
SET
@bcpCommand = @bcpCommand + @FilePath + @OutputFile + ' -c -t, -T -S'+ @@servername

exec
master..xp_cmdshell @bcpCommand

99. View the full content of a text or varchar(MAX) column in SQL Server Management Studio(IMP)

DECLARE @S varchar(max)
SELECT
@S = 'Large Data'
SELECT
@S = @S + '
'
+ OBJECT_DEFINITION(OBJECT_ID) FROM SYS.PROCEDURES

SELECT
@S AS [processing-instruction(x)] FOR XML PATH('')

Complete XML from Table:
1. Example:

SELECT
top 10 *
FROM
[dbo].[Consultants] FOR XML AUTO

2.Example:
SELECT
top 10 *
FROM
[dbo].[Consultants] FOR XML PATH 

Column Data in XML from Table:
SELECT
ReqIntID, CAST((dbo.CBO_RemoveControlCharacters_which_Are_Not_Allowed_In_XML(Description)) AS XML) AS Description
FROM
Requirements

CBO_RemoveControlCharacters_which_Are_Not_Allowed_In_XML 

100. Export Table Creation Schema with Default Values Query(IMP)

1. Generate_Create_Table_Script

100.1 Bad habits to kick : avoiding the schema prefix(IMP)

Without an explicit schema, SQL Server will first look under the schema associated with your login. This can cause problems, obviously, if you have a table called your_default_schema.foo and there is also a table in the database called dbo.foo. The DEFAULT_SCHEMA and use dbo by default.

101. Are there any disadvantages to always using nvarchar(MAX)?

1. 100 characters stored in an nvarchar(MAX) field will be stored no different to 100 characters in an nvarchar(100) field - the data will be stored inline and you will not have the overhead of reading and writing data 'out of row'. So no worries there.

2. If the size is greater than 4000 the data would be stored 'out of row' automatically, which is what you would want. So no worries there either. However...

3. You cannot create an index on an nvarchar(MAX) column. You can use full-text indexing, but you cannot create an index on the column to improve query performance. For me, this seals the deal...it is a definite disadvantage to always use nvarchar(MAX).

102. Convert Table Rows to Columns (IMP)

DECLARE @GivenTable TABLE(
                    
ColumnName NVARCHAR(MAX) NULL,
                    
Column1 NVARCHAR(MAX) NULL,
                    
Column2 NVARCHAR(MAX) NULL
             
)

INSERT
INTO @GivenTable
SELECT
'ColumnName','Column1','Column2'

INSERT
@GivenTable
SELECT
*
FROM

(

SELECT
'Row1' AS ColumnName, 'A1' as Column1, 'B1' as Column2
UNION
ALL
SELECT
'Row2' AS ColumnName, 'A2' as Column1, 'B2' as Column2
UNION
ALL
SELECT
'Row3' AS ColumnName, 'A3' as Column1, 'B3' as Column2
UNION
ALL
SELECT
'Row4' AS ColumnName, 'A4' as Column1, 'B4' as Column2
UNION
ALL
SELECT
'Row5' AS ColumnName, 'A5' as Column1, 'B5' as Column2
UNION
ALL
SELECT
'Row6' AS ColumnName, 'A6' as Column1, 'B6' as Column2
)
TEMP

DECLARE
@cols AS NVARCHAR(MAX),  @Query  AS NVARCHAR(MAX)
SELECT
@cols = STUFF((SELECT ',' + QUOTENAME([dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](ColumnName))
                   
from @GivenTable
                   
FOR XML PATH(''), TYPE
                   
).value('.', 'NVARCHAR(MAX)')
                   
,1,1,'')


SELECT
* INTO #newtable
FROM
@GivenTable

SELECT
* from #newtable

SET
@Query = N'SELECT ' + @cols + N' from
            
(
                          
SELECT ''Column1'' as ColumnNo, Column1, ColumnName AS ColumnName_T from #newtable UNION ALL
                          
SELECT ''Column2'' as ColumnNo, Column2, ColumnName from #newtable
           
) x
           
pivot
           
(
               
MAX(Column1) for ColumnName_T in ('
+ @cols + N')
           
) p '


exec
sp_executesql @Query;

DROP
TABLE #newtable

103. List All The Column With Specific Data Types in Database

SELECT *
FROM
information_schema.columns

104. Replace Repeated Characters with Single Character

DECLARE @Procedures TABLE (IDCol INT IDENTITY(1,1), ProcedureCode NVARCHAR(MAX))
INSERT
INTO @Procedures
VALUES
('')

PDATE
@Procedures SET ProcedureCode = 'AAAAA'
WHERE
IDCol = 1

WHILE
((SELECT COUNT(1) FROM @Procedures WHERE ProcedureCode LIKE '%AA%') > 0)
UPDATE
@Procedures SET ProcedureCode = REPLACE(ProcedureCode,'AA','A') WHERE IDCol = 1 

SELECT
ProcedureCode FROM @Procedures WHERE IDCol = 1

105. Email Usage in cBizOne/Exelare

Example: Let us take a Field "uuAssistantEMail" then to make it as Email Usage, we gave in Usage column as "uuAssistantEMail,EMail,Secondary"
This is not working, as Kris said he HardCoded first to Words "Email1,Email / Email2,Email" so said to Give us as like "EMail2,EMail,Secondary"

106. Candidate Status LookUp Values in cBiz and Exelare

SELECT * FROM Lookup
WHERE LookupFieldName LIKE 'Reminders.ApptSubType,Status,Status%'
ORDER
BY LookupFieldName

107. Reminder Column Names (Frontend) Differ from Database Table Name Fields

Date - Reminders.StartDateTime
Start Date - Reminders.EndDateTime
End Date - Reminders.RemDateTime

108. INSERTING data from Linked Server (IMP)

Note: Inserting large data from Linked server is more time consuming, since each and every Insert will be checked for Secutity Permission.
Solution Is: Insert N Number of Rows as one single Row on Linked Server. At Linked Server Run that Query.

UPDATE
[N80STL-SQL2.NETWORK80.COM].[cBizSoft].[dbo].[Vishnu_Update_Table_Job_Queries] SET [Query] =
'SET QUOTED_IDENTIFIER OFF;
DELETE [cBizSoft].[dbo].[Vishnu_cBizOneTicketingDBEmailCount]
INSERT INTO [cBizSoft].[dbo].[Vishnu_cBizOneTicketingDBEmailCount]
VALUES
'
+ (
SELECT
STUFF(
(
SELECT
(
SELECT ',
'
WHERE (RowNumber % 1000 != 0)
UNION

SELECT
'
INSERT INTO [cBizSoft].[dbo].[Vishnu_cBizOneTicketingDBEmailCount]
VALUES'

WHERE
(RowNumber % 1000 = 0)) + [dbo].[CBO_RemoveControlCharacters_Which_Are_Not_Allowed_In_XML](Col1)
FROM
 
(

SELECT
ROW_NUMBER() OVER (ORDER BY [SentToDisplayName])  AS 'RowNumber', '("' + [EMail] + '","' + [SentToDisplayName] + '","' + [UserIDs] + '","' + 'EMailsSent' + '",' + CAST(COUNT(1) AS NVARCHAR(10)) + ')' AS Col1
FROM
[cBizOne].[dbo].[EMailsSent]
WHERE
LEN([EMail]) > 0 AND LEN([SentToDisplayName]) > 0 AND LEN([UserIDs]) > 0 AND [EMail] LIKE '%.%' AND [EMail] LIKE '%@%' AND
(
[EMail] + [SentToDisplayName] + [UserIDs] NOT LIKE '%"%')
GROUP
BY [EMail],[SentToDisplayName],[UserIDs]
)
TEMP
ORDER
BY RowNumber FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,
1,3,'')
)
+ '

UPDATE [cBizSoft].[dbo].[Vishnu_Update_Table_Job_Queries] SET [Query] = ''''
WHERE ([Table_Name] = ''Vishnu_cBizOneTicketingDBEmailCount'' AND [Type] = ''EMailsSent'')
'

WHERE
([Table_Name] = 'Vishnu_cBizOneTicketingDBEmailCount' AND [Type] = 'EMailsSent')

Note: We are Inserting 1000 Rows at a Time as it is the Limitation in TSQL.

109. Repeat a String No. Number of Times

SELECT REPLICATE('A',10)

110. You Can Avoid Using time taking "dbo.GetReminderLinks('Status','Status',NULL)" in FROM Clause(IMP)

SELECT Reminders.RemIntID,Reminders.ApptType as Type,Reminders.ApptSubType as SubType,Reminders.Subject,Reminders.Notes,Reminders.StartDateTime AS ActivityDate,Reminders.Done,
      
SubString(Reminders.UserIDs,2,Len(Reminders.UserIDs)-2) as UserID,Consultants.ConsIntID,Consultants.Displayname as Consultant,Consultants.JobTitle,
      
Contacts.ContactIntID,Contacts.DisplayName as Contact,Contacts.CompanyName,Contacts.DirectPhone,
      
Requirements.ReqIntID,Requirements.ReqID as JobID,Requirements.JobTitle as JobJobTitle, Consultants.UserField8 as Sourcer

FROM
Reminders LEFT JOIN
Consultants ON ((SELECT COUNT(1) FROM Links L1 WHERE Reminders.RemIntID=L1.FromID AND L1.ToID=Consultants.ConsIntID) > 0) LEFT JOIN
Contacts ON ((SELECT COUNT(1) FROM Links L2 WHERE Reminders.RemIntID=L2.FromID AND L2.ToID=Contacts.ContactIntID) > 0) LEFT JOIN
Requirements ON ((SELECT COUNT(1) FROM Links L3 WHERE Reminders.RemIntID=L3.FromID AND L3.ToID=Requirements.ReqIntID) > 0)

WHERE
Reminders.RemType='Appointment' AND Reminders.ApptType='Interview'
             
/* AND ([[Reminders.ThisUserCanSee]]) */
             
/* AND ([[Consultants.ThisUserCanSee]]) */
             
/* AND ([[Consultants.UserField8]]) */
             
/* AND ([[Reminders.StartDateTime]]) */
             
/* AND ([[Reminders.UserIDs]]) */
             
/* AND ([[Reminders.Done]]) */

111. NULLIF

SELECT UserField1, CreateDate, COALESCE(NULLIF(UserField1,''),CreateDate)
FROM
Requirements

DECLARE
@Test nvarchar(10) = NULL
SELECT
NULLIF(@Test,'')
SELECT
NULLIF('','')
SELECT
NULLIF('Vishnu','')
SELECT
NULLIF('Vishnu','Vishnu')
SELECT
NULLIF(0,1)

112. If Requirements Linked Then Only Open Requirements

SELECT Count(*) as XCount,Consultants.Owners,max('Offers') as What
FROM Reminders, Links b, Consultants
WHERE Reminders.RemType='Status' AND Reminders.ApptType='Status' AND

    
(Reminders.ApptSubType = 'Offer' OR Reminders.ApptSubType = 'Hired') AND
     (Reminders.RemIntID=b.FromID and b.ToID=Consultants.ConsIntID)
    
/* AND ([[Reminders.ThisUserCanSee]]) */
    
/* AND ([[Consultants.ThisUserCanSee]]) */
    
/* AND ([[Consultants.Owners]]) */
    
/* AND ([[Consultants.UserIDs]]) */
    
/* AND ([[Reminders.StartDateTime]])  */
    
AND (
          
SELECT SUM(XCount)
          
FROM

          
(
            
SELECT COUNT(1) AS XCount WHERE (SELECT COUNT(1) FROM Links WHERE (Links.FromID = Reminders.RemIntID) AND (Links.ToID LIKE 'RQ%')) = 0
            
UNION ALL
            
SELECT COUNT(1) AS XCount FROM Requirements, Links WHERE (Links.FromID = Reminders.RemIntID) AND (Requirements.ReqIntID = Links.ToID)                                                                             AND (Requirements.ClosedDate > GetDate() OR IsDate(Requirements.ClosedDate)=0)
          
) TTT
    
    ) = 1
GROUP BY Consultants.Owners

113. Importing a large column (8000 chars) from Excel using SSIS (SQL Server Table Column Nvarchar(MAX))

Error Message:
Outputs[Excel Source Output].Columns[notes]" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
(SQL Server Import and Export Wizard)

Help Link: http://dba.stackexchange.com/questions/47248/importing-a-large-column-8000-chars-from-excel-using-ssis

We finally resolved the issue.
It turns out that SSIS calculates the length based on the first handful of rows in the excel file.
When we moved the rows with the longer data to the top the columns changed to unicode text (allowing for the extra length).

113.1. Not enough resources to display completely in Excel

Click on start>all programs->accessories->run>Excel /safe and check what happens.

Note: There is a space before the ‘/ ‘.

If it works fine in the safe mode, the issue might be due to add-ins installed. 

114. Report Customization Hours Calculation(Format):

Report Customization Hours Calculation:
Report Name:
SQL Type (Normal/Complex):
Query Preparation Time:
Procedures/Functions/Views Needed:
XML Customization and filters:
Research Work:
Testing:
Changes in Requirement:
Total Hours to Develop:

115. Changes the owner of the current database:

ALTER AUTHORIZATION ON DATABASE::Exl_addingt TO cBiz_cbizsoft

116. Make Sure assigen Empty String before Select Assignement in WHILE Loop(IMP):

DECLARE @OLD_ConsIntID NVARCHAR(max)
SET
@OLD_ConsIntID = 'Vishnu'

SELECT
TOP 1 @OLD_ConsIntID = 'Murthy'
WHERE
1=11

SELECT
@OLD_ConsIntID

117. Drop Replication Column 'msrepl_tran_version' on non Replicated Database:

SELECT 'IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''' + DC.NAME  + ''') and Type = ''D'')
           
ALTER TABLE ['
+ OBJECT_SCHEMA_NAME(SO.ID) + '].[' + SO.NAME + '] DROP CONSTRAINT [' + DC.NAME + ']'
FROM
SysObjects SO
INNER
JOIN SysColumns SC ON SO.ID = SC.ID
INNER
JOIN sys.default_constraints DC ON SO.ID = DC.Parent_object_id
   
AND SC.colid = DC.Parent_column_id

WHERE
SO.XTYPE = 'U'
   
AND SC.NAME = 'rowguid'


UNION
ALL

SELECT
'DROP INDEX [' + sys.tables.name + '].[' + sys.indexes.name + ']'
FROM
sys.tables, sys.indexes, sys.index_columns, sys.columns
WHERE
(sys.tables.object_id = sys.indexes.object_id AND sys.tables.object_id = sys.index_columns.object_id AND sys.tables.object_id = sys.columns.object_id
AND
sys.indexes.index_id = sys.index_columns.index_id AND sys.index_columns.column_id = sys.columns.column_id)
AND
sys.columns.name = 'rowguid'

UNION
ALL

SELECT
'IF EXISTS (SELECT * FROM dbo.syscolumns where id = OBJECT_ID(N''' + SO.NAME + ''') and Name = ''rowguid'')
       
ALTER TABLE ['
+ OBJECT_SCHEMA_NAME(SO.ID) + '].[' + SO.NAME + '] DROP COLUMN [rowguid]  '
FROM
SysObjects SO
INNER
JOIN SysColumns SC ON SO.ID = SC.ID
WHERE
SO.XTYPE = 'U'
   
AND SC.NAME = 'rowguid'

ORDER
BY 1 

118. If Requirement Contact is Changed, then also change the Linked Status Contact:

UPDATE L1 SET L1.ToID = Requirements.LinkToIntID
FROM
Reminders, Links b, Links d, Links l1, Contacts, Requirements  
WHERE
Reminders.RemType='Status' AND Reminders.ApptType='Status' AND
       
(Reminders.RemIntID=b.FromID and b.ToID=Contacts.ContactIntID) AND
       
(Reminders.RemIntID=d.FromID and d.ToID=Requirements.ReqIntID) AND
       
(L1.FromID = Reminders.RemIntID AND L1.ToID LIKE 'CN%') AND
       
(L1.ToID != Requirements.LinkToIntID)

119. How to query the names of encrypted stored procedures?

SELECT ROUTINE_NAME
FROM
INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_DEFINITION IS NULL
ORDER
BY ROUTINE_NAME ASC 

119. Logical Processing Order of the SELECT statement.

  1. FROM

  2. ON

  3. JOIN

  4. WHERE

  5. GROUP BY

  6. WITH CUBE or WITH ROLLUP

  7. HAVING

  8. SELECT

  9. DISTINCT

  10. ORDER BY

  11. TOP

119.1. With RollUp

select CName, sum(Value) as Value, sum(Value1) as Value1
from
(
select
'aaa' as CName, 10 Value, 10 Value1
union
all
select
'bbb' as CName, 10 Value, 34 Value1
union
all
select
'ccc' as CName, 10 Value, 22 Value1
union
all
select
'aaa' as CName, 23 Value, 44 Value1
union
all
select
'bbb' as CName, 3 Value, 37 Value1
union
all
select
'ccc' as CName, 14 Value, 14 Value1
)
t
group
by CName
WITH
ROLLUP

121. Difference between ntext , text, and image data types Vs nvarchar(max), varchar(max), and varbinary(max)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

122. Free SQL Server Health Check (sp_Blitz).

Download the Following File and run the procedures on you Local Database Only (Not on Hosting Server)

First Responder Kit 20161115.

1. sp_Blitz.sql
      
EXEC [dbo].[sp_Blitz]
2. sp_BlitzCache.sql
      
EXEC dbo.sp_BlitzCache
3. sp_BlitzWho
4. sp_BlitzFirst.sql
      
EXEC [dbo].[sp_BlitzFirst]
5. sp_BlitzIndex.sql
      
EXEC dbo.sp_BlitzIndex
6. sp_BlitzTrace.sql
      
EXEC sp_BlitzTrace @SessionId = @@SPID, @Action = 'start', @TargetPath = 'D:\Main\SQL\XEvents\Traces\'
      
GO
      
SELECT name, state_desc
      
FROM sys.databases
      
GO
      
EXEC sp_BlitzTrace @Action = 'stop'
      
GO
      
EXEC sp_BlitzTrace @Action = 'read'
      
GO
      
EXEC sp_BlitzTrace @Action = 'drop'
      
GO    

123. Delete BackUp file from the server.

EXECUTE master.dbo.xp_delete_file 0,N'G:\1DemoDB_Vishnu.bak'

124. Learn to use Union, Intersect, and Except Clauses.

Example: Learn to use Union, Intersect, and Except Clauses

125. Get a List of all Primary Keys in a Database with IndexType (NONCLUSTERED/CLUSTERED).

SELECT TABLE_NAME, ISNULL(CONSTRAINT_NAME, TABLE_NAME + '_PK') AS CONSTRAINT_NAME,
ISNULL
(COLUMN_NAMES, (SELECT TOP 1 '[' + COLUMN_NAME + ']' FROM information_schema.COLUMNS WHERE TABLE_NAME = TEMP1.TABLE_NAME AND ORDINAL_POSITION = 1)) AS COLUMN_NAMES,
ISNULL
((SELECT 'WITH DROP_EXISTING' WHERE CONSTRAINT_NAME IS NOT NULL),'') AS With_Condition,
ISNULL
(CAST((SELECT TOP 1 'CLUSTERED' FROM sys.indexes WHERE (OBJECT_NAME(object_id) = TABLE_NAME AND type_desc = 'CLUSTERED')) AS NVARCHAR(max)), 'NONCLUSTERED') AS IndexType
FROM

(

SELECT
TABLE_NAME, (SELECT TOP 1 CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_NAME = T.TABLE_NAME) AS CONSTRAINT_NAME,
(

      
STUFF((
      
SELECT  ', [' + COLUMN_NAME + ']'
      
FROM information_schema.KEY_COLUMN_USAGE
      
WHERE TABLE_NAME = T.TABLE_NAME
      
ORDER BY TABLE_NAME, ORDINAL_POSITION
      
FOR XML PATH('')), 1, 2, '')

)
AS COLUMN_NAMES
FROM
information_schema.TABLES T
WHERE
(T.TABLE_TYPE = 'BASE TABLE')
)
TEMP1

126. Alter user dbo.

Alter a SQL user’s database account; more specifically speaking a Login name’s database user name

Use [database_name]
go

sp_changedbowner
'cBiz_cbizsoft'

127. Using MERGE in SQL Server to insert, update and delete at the same time

In a typical data warehousing application, quite often during the ETL cycle you need to perform INSERT, UPDATE and DELETE operations on a TARGET table by matching the records from the SOURCE table.

Beginning with SQL Server 2008, now you can use MERGE SQL command to perform these operations in a single statement.

The MERGE statement basically merges data from a source result set to a target table based on a condition that you specify.

Note: Key Words MERGE, BY TARGET AND BY SOURCE
Example:


--Create a Target table
 
DECLARE @Target_Table TABLE (ProductID INT PRIMARY KEY, ProductName NVARCHAR(100), Rate MONEY) 
 
INSERT INTO @Target_Table VALUES (1, 'Tea', 10.00), (2, 'Coffee', 20.00), (3, 'Muffin', 20.00), (4, 'Biscuit', 40.00)
--Create Source table
 
DECLARE @Update_Insert_Delete_Table TABLE (Operation  NVARCHAR(100), ProductID INT, ProductName NVARCHAR(100), Rate MONEY )
 INSERT INTO @Update_Insert_Delete_Table VALUES ('Update', 3, 'Muffin', 30.00),  ('Delete', 1, 'Tea', 10.00),  ('Insert', 5, 'Pizza', 60.00)

 
SELECT * FROM @Target_Table
 
SELECT * FROM @Update_Insert_Delete_Table

 
-----------------------
 --Synchronize the TARGET table with
 
--refreshed data from SOURCE table
 
MERGE @Target_Table AS T
 
USING @Update_Insert_Delete_Table AS S 
 
ON  (T.ProductID = S.ProductID) 
 
--When records are matched, update
 
--the records if there is any change
 
WHEN MATCHED AND (S.Operation = 'Update') THEN 
 
UPDATE SET T.Rate = S.Rate 
 
--When no records are matched, insert
 
--the incoming records from SOURCE
 
--table to TARGET table
 
WHEN NOT MATCHED BY TARGET AND S.Operation = 'Insert' THEN 
 
INSERT  (ProductID, ProductName, Rate) 
 
VALUES  (S.ProductID, S.ProductName, S.Rate)
 
--When there is a row that exists in TARGET table and
 
--same record does not exist in SOURCE table
 
--then delete this record from TARGET table
 
WHEN MATCHED AND S.Operation = 'Delete' THEN
 
DELETE
 
--$action specifies a column of type nvarchar(10)
 
--in the OUTPUT clause that returns one of three
 
--values for each row: 'INSERT', 'UPDATE', or 'DELETE',
 
--according to the action that was performed on that row
 
OUTPUT  $action, DELETED.*, INSERTED.*;

 
SELECT * FROM @Target_Table

1. MERGE statement with join conditions that produce unexpected results.
MERGE Target AS T USING Source AS S
ON (T.EmployeeID = S.EmployeeID AND T.EmployeeName LIKE 'S%' AND S.EmployeeName LIKE 'S%' )
WHEN NOT MATCHED BY TARGET THEN
INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED THEN
UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE THEN
DELETE OUTPUT $action, Inserted.*, Deleted.*;

Solution:
Reducing the number of rows in the input stream early in the process by specifying the additional search condition to the ON clause (for example, by specifying ON T.EmployeeID = S.EmployeeID AND T.EmployeeName LIKE 'S%' AND S.EmployeeName LIKE 'S%' ) might seem to improve query performance. However, doing so can cause unexpected and incorrect results. Because the additional search conditions specified in the ON clause are not used for matching the source and target data, they can be misapplied.

2. INSERT, UPDATE, DELETE Order of Execution in Merge.
For every insert, update, or delete action specified in the MERGE statement, SQL Server fires any corresponding AFTER triggers defined on the target table, but does not guarantee on which action to fire triggers first or last.

It expects a unique value to be compared.


Help Link

128. Getting the actual data size per row in a SQL Server table

declare @table nvarchar(128)
declare @idcol nvarchar(128)
declare
@sql nvarchar(max)

--initialize those two values

set
@table = 'Consultants'
set
@idcol = 'ConsIntID'
set
@sql = 'select ' + @idcol

select
@sql = @sql + ', isnull(datalength(' + name + '), 1) as ' + name
       
from sys.columns where object_id = object_id(@table)

set
@sql = @sql + ', (0'

select
@sql = @sql + ' + isnull(datalength(' + name + '), 1)'
       
from sys.columns where object_id = object_id(@table)

set
@sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'

--PRINT @sql

exec
(@sql)

129. Get all UserID's from a GroupName for View with LoggedInUser.

SELECT *
FROM
XUserGroups
WHERE
(GroupType = 'Departments')
ORDER
BY GroupName
 

select
*
FROM
XUserGroups G1,XUserGroups G2 
WHERE

(
G1.GroupType = 'Departments') AND 
(
',' + G1.UserID + ',' LIKE [LoggedInUser]) AND 
(
G2.GroupName = G1.GroupName)  AND 
(
G2.GroupType = G1.GroupType)

130. Get client IP address in the Database record 'client_net_address'.

ALTER table [dbo].[SaveSets] add
[SQLLoginID] [nvarchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL


ALTER
TABLE [dbo].[SaveSets] WITH NOCHECK ADD
CONSTRAINT
[DF_AuditTrailCompanies_SQLLoginID] DEFAULT (CAST(CONNECTIONPROPERTY('client_net_address') AS NVARCHAR(40))) FOR [SQLLoginID]

131. Import .CSV or .xls in to a table and insert from there to Consulants.

INSERT INTO [dbo].[Consultants] ([ConsIntID], [ConsultantID],[UserField1], [UserField2],[FirstName], [LastName] ,[Email1], [MobilePhone],[JobTitle] ,[VisaStatus],[ResumeFile], [UserIDs] ,[CreateDate],[EditDate])
SELECT
ConsIntid, ConsIntid AS ConsultantID,[Resume_ID],Resume_File1, [First_Name], [Last_Name],[Email_ID], [Phone], [Resume_Title], [Work_Status], [Resume_File], USERIDS, CreateDate, EditDate
FROM
(
SELECT
  'CS' + REPLICATE('0',8-LEN(RowNumberID)) + RowNumberID AS ConsIntid, ConsultantID,[Resume_ID],[Resume_File] as Resume_File1, [First_Name], [Last_Name], replace([Email_ID],'''', '') as [Email_ID], [Phone], [Resume_Title], [Work_Status], replace([Resume_File], 'CbizResumes\', '') as [Resume_File], ',Admin,' as USERIDS, getdate() As CreateDate, getdate() as EditDate
FROM
(
SELECT
cast(ROW_NUMBER() OVER (ORDER BY [Resume_ID] desc) as nvarchar(max))  AS 'RowNumberID', *
from
[EproCanSQL]
)
TT
)
KK 

DECLARE @Countt INT
SET
@Countt = 1

WHILE
(@Countt < 100000)
BEGIN
SET
NOCOUNT ON;
UPDATE
TOP (1) [dbo].[Consultants] SET ConsultantID = [dbo].[GenerateConsultantID](FirstName, LastName)
WHERE
ConsultantID LIKE 'CS00%'

SET
@Countt = @Countt + 1
END

132. Update dice Account information.

SELECT *
FROM
[Exl_Aquinas].[dbo].[Users]
WHERE
RecType = '01' and [AppPermissions] like '%;Summer2019!;%'

SELECT
[AppPermissions], REPLACE(CAST([AppPermissions] AS NVARCHAR(MAX)),';Summer2018!;',';Summer2019!;')
FROM
[Exl_Aquinas].[dbo].[Users]
WHERE
RecType = '01' and [AppPermissions] like '%;Summer2018!;%'

UPDATE TOP (1) [Exl_Aquinas].[dbo].[Users] set [AppPermissions] = REPLACE(CAST([AppPermissions] AS NVARCHAR(MAX)),';Summer2018!;',';Summer2019!;')
WHERE
RecType = '01' and [AppPermissions] like '%;Summer2018!;%'

133. Turning a Comma Separated string into individual rows.

;WITH tmp(ConsIntID, DataItem, Categories) AS
(

   
SELECT ConsIntID,
       
CAST(LEFT(Categories, CHARINDEX(',', Categories + ',') - 1) AS NVARCHAR(MAX)),
       
STUFF(Categories, 1, CHARINDEX(',', Categories + ','), '')
   
FROM [dbo].[Consultants]
   
WHERE LEN(ISNULL(Categories, '')) > 0

   
UNION all

   
SELECT ConsIntID,
       
CAST(LEFT(Categories, CHARINDEX(',', Categories + ',') - 1) AS NVARCHAR(MAX)),
       
STUFF(Categories, 1, CHARINDEX(',', Categories + ','), '')
   
FROM tmp   
   
WHERE Categories > ''

)


SELECT
DataItem AS Categories, COUNT(1) AS Count1
FROM
tmp
GROUP
BY DataItem

134. using Table variable with sp_executesql.(IMP IMP)

if exists (select * from sys.types where name = 'TestTableType')
drop
type TestTableType
create
type TestTableType as table (id int)
GO
declare
@t TestTableType
insert
@t select 6*7

exec
sp_executesql N'select * from @var', N'@var TestTableType readonly', @t

135. Create read only User for database.

USE master;
GO
CREATE
LOGIN Vishnu_Exl_VishnuTest1_Read WITH PASSWORD = '******';
GO
USE
[Exl_VishnuTest1];
GO
CREATE
USER Vishnu_Exl_VishnuTest1_Read FOR LOGIN Vishnu_Exl_VishnuTest1_Read;
GO
ALTER
ROLE db_datareader ADD MEMBER Vishnu_Exl_VishnuTest1_Read;
GO
DENY
INSERT, UPDATE, DELETE, EXECUTE TO Vishnu_Exl_VishnuTest1_Read;
GO