Thursday, October 27, 2011

How to find tables column list

We can use the following query to find a list of tables that contain a specific column name in entire database. 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS where  COLUMN_NAME='column name'

If you are unsure what is the exact column name , you can use the following query: 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS where  COLUMN_NAME='column name'



How to find the Triggers details in Database

We  can use the following query to find a list of  all the triggers along with trigger details in the specific database:

select
"Table"=P.Name,
"Trigger Name"=O.name,
"Trigger Date"=O.refdate,
"Defn"=CASE C.encrypted WHEN 0 THEN C.text ELSE '<< ENCRYPTED >>' END
from
syscomments C
INNER JOIN sysobjects O ON (C.id = O.id)
INNER JOIN sysobjects P ON (O.parent_obj = P.id)
where

O.xtype = 'TR'

How to find list of all the triggers in Database

To find a list of  all the triggers in the specific database , we  can use the following query:

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'




Wednesday, October 26, 2011

How to find if a particular field used in SQL SPs

If you want to find if a particular field been used in Stored Procedure , you can do this using the INFORMATION_SCHEMA.ROUTINES view and filter based on the ROUTINE_TYPE='PROCEDURE' , following query will search to find if field1 been used in any stored procedure in the database.

SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%field1%'     
AND ROUTINE_TYPE='PROCEDURE'

Tuesday, October 25, 2011

eConnect error 609

eConnect error 609 , SQL error occurred inserting into the RM Keys Master Table - RM00401, RMDTYPAL DOCNUMBR DOCDATE BACHNUMB CUSTNMBR.

You can get this error if you are calling the eConnect method taRMTransaction to create an invoice or debit memo in Microsoft Dynamics GP. This error could occur because one of the following reasons , so you can check which one of those reasons match with your case and you can resolve this error easily:

  1. Duplicate entry in RM00401, it mean you are trying to insert an existing document number / document type (1=Invoice,3=Debit Memo etc) into RM00401, in this case you need to check why your process try to use an exists document number / document type.
  2. Wrong format of document date, in the RM00401 table there is constraint (CK__RM00401__DOCDATE__47E69B3D) on Document Date field (DOCDATE) to force the system to accept only the date part in this column, so if you pass date with time it will give an error , so you need to pass only the date , you can use something like:


set @DocDate=convert (date,@DocDate,101)


 

insert RM00401

                                (

                                DOCNUMBR,

                                RMDTYPAL,

                                DCSTATUS,

                                BCHSOURC,

                                CUSTNMBR,

                                DOCDATE

                                )

                                select

                                                @I_vDOCNUMBR,

                                                @I_vRMDTYPAL,

                                                1,

                                                'RM_Sales',

                                                @I_vCUSTNMBR,

                                                @I_vDOCDATE

Monday, October 17, 2011

How to find Special Characters in SQL


If you are developing a user interface and want to stop the user from using the special character in specific field , you can develop stored procedure to be used in the validation.

To define the special characters we can use the ASCII table to find the ranges of the special  characters, from that table we can easily identify the ranges which been used to represent the  special characters:

ASCII Code special characters : (33-47) , (58-74), (91-96),(123-255)

In SQL we can use ASCII function (which returns the ASCII code value of a character expression), to find the ASCII codes and check if it is in the one of the specified ranges above, if the code was in these ranges it mean the it is an special character.

You can use the following SP to validate the special characters , this SP has one input parameter represent the value which you want to validate and it has two output parameters, @STATUS to indicate if there is special characters or not (=0 no special characters, =1 special characters) ,@SpecialCharacters will return the first special character.

CREATE PROCEDURE Find_Special_Characters 
 -- Add the parameters for the stored procedure here 
 @INPUTST AS VARCHAR (250), 
 @STATUS AS INT OUTPUT, -- =0 no SpecialCharacters, =1 SpecialCharacters 
 @SpecialCharacters AS VARCHAR (50) OUTPUT 
AS 
BEGIN 
 -- SET NOCOUNT ON added to prevent extra result sets from 
 -- interfering with SELECT statements. 
 SET NOCOUNT ON; 
  
   
 set @STATUS=0 
 set @SpecialCharacters='' 
  
  
 declare @len integer 
 declare @idx integer 
 declare @ascValue integer 
 declare @stopflg integer 
  

 set @stopflg=0 
 set @len=len(rtrim(ltrim(@INPUTST))) 
 set @idx=1 
  
 while @idx<=@len and @stopflg=0 
 begin 
  set @ascValue = ascii(substring(@INPUTST, @len-(@idx-1),1) ) 
   
  IF (@ascValue BETWEEN 33 AND 47)
  OR (@ascValue BETWEEN 58 AND 64) 
  OR (@ascValue BETWEEN 91 AND 96) 
  OR (@ascValue BETWEEN 123 AND 255)   
    begin 
set @stopflg=1 
           set @STATUS=1 
          set @SpecialCharacters=char(@ascValue)  
    end  
 set @idx=@idx+1 
 end 
  

Sunday, October 16, 2011

How to find the version of SQL Server

How to find which version of:

1- SQL Server 2008 :
To find which version of Microsoft SQL Server 2008 is installed, connect to SQL Server 2008 by using SQL Server Management Studio ,then run the following query.
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
The following results are returned:
The product version (for example, 10.0.2531.0)
The product level (for example, SP1)
The edition (for example, Enterprise Edition (64-bit))

Release
SQL Version
RTM
2007.100.1600.0
SQL Server 2008 Service Pack 1
2007.100.2531.0

2- SQL Server 2005:
To find which version of Microsoft SQL Server 2005 is installed, connect to SQL Server 2008 by using SQL Server Management Studio ,then run the following query.
SELECT  SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
The following results are returned:
The product version (for example, 9.00.1399.06)
The product level (for example, RTM)
The edition (for example, Enterprise Edition)


Release
SQL Version
RTM
2005.90.1399
SQL Server 2005 Service Pack 1
2005.90.2047
SQL Server 2005 Service Pack 2
2005.90.3042
SQL Server 2005 Service Pack 3
2005.90.4035

3- SQL Server 2000 is running
To find which version of Microsoft SQL Server 2005 is installed, connect to SQL Server 2008 by using SQL Server Management Studio ,then run the following query.
SELECT  SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
The following results are returned:
The product version (for example, 8.00.534)
The product level (for example, "RTM" or "SP2")
The edition (for example, "Standard Edition").

Release
SQL Version
RTM
2000.80.194.0
SQL Server 2000 SP1
2000.80.384.0
SQL Server 2000 SP2
2000.80.534.0
SQL Server 2000 SP3
2000.80.760.0
SQL Server 2000 SP3a
2000.80.760.0
SQL Server 2000 SP4
2000.8.00.2039

Tuesday, October 11, 2011

How to Restart SQL Jobs automatically


If you used SQL jobs in critical environment where the process should continually running under any circumstances, in this case system should automatically response to any SQL job failure and you to be alerted so you can monitor the process and you will be able to fix the issues quickly.

 to achieve the previous requirement we can create a SQL job to monitor the other SQL jobs and restart them Immediately after the SQL job failure also this job can send emails to alert the process owner.

To get information about the current status of SQL jobs we can use the xp_sqlagent_enum_jobs which is an  extended stored procedure can be found in the master database. xp_sqlagent_enum_jobs extended stored procedure can be used to return information for all jobs, to return the job information for jobs own by a particular login, or the job information for a particular job identification number. The State output parameter of this SP will contain the current status of SQL jobs:

0  Returns only those jobs that are not idle or suspended.
1  Executing.
2  Waiting for thread.
3  Between retries: between retries for jobs that have failed through SQL-related issues
4  Idle.
5  Suspended.
7  Performing completion actions

After we identify the SQL job status we can use that to restart the SQL job using  sp_start_job stored procedure if the job was failed. After we restart the SQL job we can send an email to process owner using sp_send_dbmail stored procedure.

In the following SP we are monitoring three SQL jobs (SQL-Job1,SQL-Job2 & SQL-Job3) ,  and to automate the monitoring process we can create a SQL Job to run this SP every one minute on daily basis.


CREATE PROCEDURE [dbo].[Monitor_SQL_Jobs]

AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    declare @job_id uniqueidentifier
    declare @jobstatus as int --=1 Job runnig
    declare @name as varchar(100)
   
    set @jobstatus=0
    set @name=''


declare @EDBNAME AS VARCHAR (10)
declare @body1 AS VARCHAR (100)
declare @subject1 AS VARCHAR (100)

declare @exestatment as varchar(500)

 DECLARE SQL_Job_loop CURSOR
 STATIC OPTIMISTIC FOR 
 select job_id,name from [msdb].dbo.sysjobs where name  in
('SQL-Job1',
'SQL-Job2',
'SQL-Job3')
    
 OPEN SQL_Job_loop
 FETCH FIRST FROM is_SQL_Job_loop INTO @job_id,@name
 WHILE @@FETCH_STATUS=0
BEGIN
            
create table #enum_job (
Job_ID uniqueidentifier,
Last_Run_Date int,
Last_Run_Time int,
Next_Run_Date int,
Next_Run_Time int,
Next_Run_Schedule_ID int,
Requested_To_Run int,
Request_Source int,
Request_Source_ID varchar(100),
Running int,
Current_Step int,
Current_Retry_Attempt int,
State int
)      
insert into #enum_job
 exec master.dbo.xp_sqlagent_enum_jobs 1,multiuser,@job_id

select @jobstatus=isnull(State,0) from #enum_job

if @jobstatus is null set @jobstatus=8

if @jobstatus  in (3,4,5)
begin
EXEC sp_start_job @job_name = @name

select @subject1= 'Monitor SQL Jobs - Restart ' +@name 
select @body1= 'Monitor SQL Job has restarted successfully the follwoing SQL Job: ' +@name 

EXEC msdb..sp_send_dbmail @profile_name='SQL Notiifaction mail',
@recipients='youremail@yahoo.com',
@subject=@subject1,
@body=@body1,
@body_format = 'HTML'   
end

drop table #enum_job


FETCH NEXT FROM SQL_Job_loop INTO @job_id,@name
END        
CLOSE SQL_Job_loop
DEALLOCATE SQL_Job_loop        

Monday, October 10, 2011

How to Exit a T-SQL Cursor When Condition is met



If you are using cursor and you want to stop the cursor when it meet specific condition, to achieve that we can use additional condition in the WHILE statement, along with @@FETCH_STATUS the new condition will control when the loop has to stop.

In the following example @StopLoop parameter used to control the cursor , this cursor will stop in two conditions, this first one when @@FETCH_STATUS<>0 and this mean all records has been processed and the second condition when @StopLoop<>1.

   


DECLARE @Param1 AS INT
DECLARE @Param2 AS VARCHAR
DECLARE @Param3 AS VARCHAR

DECLARE @StopLoop AS INT

SET @StopLoop=0

DECLARE NEWLOOP CURSOR READ_ONLY
FOR

SELECT
Field1,
Field2,
Field3
FROM Table

OPEN NEWLOOP

FETCH NEXT FROM NEWLOOP INTO @Param1, @Param2,@Param3

WHILE @@FETCH_STATUS = 0 AND @StopLoop=0
BEGIN

{…… SQL Statement to process the data …...}
{…… SQL Statement to process the data …...}

IF @Param1 = 1 AND @Param2='stop'
BEGIN
SET @StopLoop = 1
END

FETCH NEXT FROM NEWLOOP INTO @Param1, @Param2,@Param3

END

CLOSE NEWLOOP
DEALLOCATE NEWLOOP

http://www.dynamicssol.com/ShowArticle.aspx?ID=10



How to use Join in SQL Delete statement

 In this example we can see how to use inner join in delete statement,
While use the inner join in delete we need to specify the  table name (which we are going to delete from)after the DELETE word and this is very important.

delete DTL FROM [Table1] DTL inner join Table2 TRNS on DTL.Field1=TRNS.Field1
where DTL.Field2='...'  

SSRS - How to Parameterizing the SQL Query

We need to create separated dataset to handle the pre defined list in that dataset we will use simple select statement to define the li...