Archive

Archive for the ‘SQL’ Category

SQL query to check locking process.

May 17th, 2015 1 comment

Here is a useful query to check user section that cause blocking / locking.

SELECT
d1.session_id,
d3.[text],
d1.login_time,
d1.login_name,
d2.wait_time,
d2.blocking_session_id,
d2.cpu_time,
d1.memory_usage,
d2.total_elapsed_time,
d2.reads,d2.writes,
d2.logical_reads,
d2.sql_handle
FROM sys.dm_exec_sessions d1
JOIN sys.dm_exec_requests d2 ON d1.session_id=d2.session_id
CROSS APPLY sys.dm_exec_sql_text(d2.sql_handle) d3

Categories: Development, SQL Tags: ,

SQL Query Syteline 9

February 17th, 2015 No comments

In Syteline 9, there is one significant database schema change.  All major tables like item are replaced with a view and _mst table.  There are some context variables need to be set, before you can run query against to the views.  Otherwise query to the view will return no data.  And here is the variable declaration, with sample query after that.

DECLARE @Br NVARCHAR(8)

SET @Br = ‘SiteName’’

DECLARE @Context NVARCHAR(100)

SET @Context = @Br

DECLARE @BinVar VARBINARY(128)

SET @BinVar = CONVERT (VARBINARY(128), @Context)

set CONTEXT_INFO @BinVar

 

 

select co.slsman,co.co_num,co.type, co.order_date, coitem.co_line, coitem.item, coitem.qty_ordered_conv,coitem.price_conv,co.exch_rate

, ca.name, coitem.qty_ordered_conv * coitem.price_conv ‘Amount’, coitem.co_release

from coitem

join co on co.co_num = coitem.co_num

left join custaddr ca on ca.cust_num = co.cust_num and ca.cust_seq = co.cust_seq

where isnull(co.slsman,”) = ”

Update 2/10/2015

You may now just call this Sp.

DECLARE @Infobar InfobarType;
EXEC [dbo].[SetSiteSp] ‘CCSSL’, @Infobar OUTPUT

Categories: Development, SQL Tags:

Send Email from SQl Database

August 7th, 2014 No comments

This is a great blog post regarding how to setup SQL Mail.  Need to keep for reference.

SQL SERVER – 2008 – Configure Database Mail – Send Email From SQL Database

Categories: SQL Tags: ,

Delete voided check and reset the next check number in AP

April 27th, 2014 No comments

Sometimes a user will accidentally type in a wrong number in the starting check number in A/P check printing and posting. If that check number is higher than the last check number used, the system will prompt to void all the check numbers in between. If that prompt is answered "ok", this will result in a large number of voided checks in the Bank Reconciliation and the system will not allow those numbers to be used.

This problem can be fixed in one of two ways.

The first is to go into the bank reconciliation and delete those voided checks one by one until they get back to the correct starting check number.

The second way is to use SQL Query to programmatically delete those voided checks.

 

/* This script is used to delete a range of check numbers from the glbank table */

declare @commit int, @rows int, @check_num GlCheckNumType

——————————————————————-

/* INSTRUCTIONS: CHANGE THE @commit VARIABLE TO VIEW OR COMMIT CHANGES

AND ENTER A MAX CHECK NUMBER. */

SET @commit = 0 — 0=View; 1=Commit the update changes

SET @check_num = 1055 — Enter highest check number wanted in SL

——————————————————————-

— VIEW CHECK RECORDS THAT WILL BE DELETED

select * from glbank

where check_num > @check_num and type = ‘C’

set @rows=@@rowcount

if @commit=0

begin

if @rows > 0 select [Results]=’Viewing record(s) to be deleted.’

else select [Results]=’No matching records found.’

end

else

begin

— DELETE CHECK RECORDS

delete from glbank

where check_num > @check_num and type = ‘C’

select [Results]= dbo.cstr(@@rowcount) + ‘ Glbank record(s) deleted.’

end

 

Progress version

for each (database name).glbank where check-num > xxxxxxxxx and type = "C":

display glbank with 2 col.

Run the query. If the checks that display are the ones that need to be deleted, then run the following:

for each (database name).glbank where check-num > xxxxxxxx and type = "C":

delete glbank.

This will reset the starting check number back to the original check.

SQL: Select … for XML

May 23rd, 2012 No comments

The Select … for XML can be useful.  Let say that you want to list out Job Order information, one job per line, and one of the field will be WC, and you want to show all WCs for the job, in the format like WC1, WC2, WC3, …  Here is the select statement will work the trick.

Select j.job, j.suffix, j.order_date, j.item, j.qty_released,

(Select jr.wc + ‘,  ‘  as ‘text()’ from jobroute jr where jr.job = j.job and jr.suffix = j.suffix

  for XML path(”)) as ‘WC’

from job j where j.status = ‘R’

Categories: Development, SQL Tags: ,

Get Only Date from DateTime

April 4th, 2012 No comments
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

There is also a few useful UDF(User Defined Function) in Syteline

ConvDate (@pInputDate  DateType, @pFormat   NVARCHAR(10))

Sample

SELECT ConvDate(GetDate(), ‘MM/DD/YYYY’)

Another useful one, DayEndOf

ALTER FUNCTION [dbo].[DayEndOf] (

  @Date DATETIME

) RETURNS DATETIME

AS

BEGIN

    –  This function takes the input date and extends the time portion forward

    — to the last possible moment of that day, just before midnight of the next day.

    — A null in yields a null out. It is useful for doing

    — high-range comparisons where only the day matters and offers an alternative to the

    — DATEDIFF built-in. The first 4 bytes of a datetime field are the date and

    — the second four the time.

   
    RETURN case when @Date = CONVERT(DATETIME, ‘9999-12-31 23:59:59.998’, 121) then @Date

       else dateadd(ms, -2, dbo.MidnightOf( dateadd(day, 1, @Date) ) )

       end

END

Categories: Development, SQL Tags:

Calling a Synchronous Event within a SP Transaction and Handling Failure

March 20th, 2012 No comments

First, determine the current site, after which you must name a configuration, by convention:

DECLARE @Site SiteType
SELECT @Site = site FROM parms

Then determine the current SessionId:

 

DECLARE @SessionId RowPointerType
SET @SessionId = dbo.SessionIdSp()

Finally, add the procedure code:

 

BEGIN TRANSACTION
UPDATE coitem
SET due_date = dbo.CalcDueDate(@Parm1, @Parm2)
WHERE coitem.co_num = @CoNum
AND coitem.co_line = @CoLine
AND coitem.co_release = @CoRelease
SET @MyEventParmId = NEWID()
EXEC InsertEventInputParameterSp @MyEventParmId, ‘CoNum’, @CoNum
EXEC InsertEventInputParameterSp @MyEventParmId, ‘CoLine’, @CoLine
EXEC InsertEventInputParameterSp @MyEventParmId, ‘CoRelease’, @CoRelease

DECLARE
@anyHandlersFailed [tinyint],
@result [nvarchar](4000),
@Infobar [nvarchar](4000)
EXEC @Severity = FireEventSp
@eventName = SetCoitemDueDate’,
@configName = ‘SyteLine’,
@sessionID = @SessionID,
@eventTrxId = null,
@eventParmId = @MyEventParmID OUTPUT,
@transactional = 0,
@anyHandlersFailed = @anyHandlersFailed output,
@result = @result output,
@Infobar = @infobar output
IF @Severity > 0
BEGIN
EXEC RaiseError @Infobar, @Severity
ROLLBACK TRANSACTION
END

COMMIT TRANSACTION

Categories: Development, SQL Tags: ,

Date Time for Multi-Site

February 9th, 2012 No comments

Something to remember, in programming in multiple site environment, if you have site that has differ time zone than the server time zone, remember to use GetSiteDate function, instead of directly GETDATE().  Below is code sample.

   SET @PrintDate = dbo.GetSiteDate(GETDATE())

Syteline Performance Tuning–Part 1

January 21st, 2012 No comments

 

1) Update Statistics

You should always run the below command nightly

Exec sp_updatestats

2) Rebuild Index for key tables

It is worth to rebuild index for key tables regularly, like once a week.

DBCC DBREINDEX (ledger)
GO
DBCC DBREINDEX (item)
GO
DBCC DBREINDEX (customer)
GO
DBCC DBREINDEX (matltran)
GO
DBCC DBREINDEX (journal)
GO
DBCC DBREINDEX (ledger_all)
GO
DBCC DBREINDEX (matltran_amt)
GO

3) Defragment Index

Below script will defragment any index with over 20% logical fragmentation.  This should set to run weekly.

/*Perform a ‘USE <database name>’ to select the database in which to run
the script.*/
— Declare variables
SET NOCOUNT ON
DECLARE @tablename VARCHAR (128)
DECLARE @execstr VARCHAR (255)
DECLARE @objectid INT
DECLARE @indexid INT
DECLARE @frag DECIMAL
DECLARE @maxfrag DECIMAL
— Decide on the maximum fragmentation to allow
SELECT @maxfrag = 20.0
— Declare cursor
DECLARE tables CURSOR FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ‘BASE TABLE’
— Create the table
CREATE TABLE #fraglist (
ObjectName CHAR (255),
ObjectId INT,
IndexName CHAR (255),
IndexId INT,
Lvl INT,
CountPages INT,
CountRows INT,
MinRecSize INT,
MaxRecSize INT,
AvgRecSize INT,
ForRecCount INT,
Extents INT,
ExtentSwitches INT,
AvgFreeBytes INT,
AvgPageDensity INT,
ScanDensity DECIMAL,
BestCount INT,
ActualCount INT,
LogicalFrag DECIMAL,
ExtentFrag DECIMAL)
— Open the cursor
OPEN tables
— Loop through all the tables in the database
FETCH NEXT
FROM tables
INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
— Do the showcontig of all indexes of the table
INSERT INTO #fraglist
EXEC (‘DBCC SHOWCONTIG (”’ + @tablename + ”’)
WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS’)
FETCH NEXT
FROM tables
INTO @tablename
END
— Close and deallocate the cursor
CLOSE tables
DEALLOCATE tables
— Declare cursor for list of indexes to be defragged
DECLARE indexes CURSOR FOR
SELECT ObjectName, ObjectId, IndexId, LogicalFrag
FROM #fraglist
WHERE LogicalFrag >= @maxfrag
AND INDEXPROPERTY (ObjectId, IndexName, ‘IndexDepth’) > 0
— Open the cursor
OPEN indexes
— loop through the indexes
FETCH NEXT
FROM indexes
INTO @tablename, @objectid, @indexid, @frag
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ‘Executing DBCC INDEXDEFRAG (0, ‘ + RTRIM(@tablename) + ‘,
‘ + RTRIM(@indexid) + ‘) – fragmentation currently ‘
+ RTRIM(CONVERT(varchar(15),@frag)) + ‘%’
SELECT @execstr = ‘DBCC INDEXDEFRAG (0, ‘ + RTRIM(@objectid) + ‘,
‘ + RTRIM(@indexid) + ‘)’
EXEC (@execstr)
FETCH NEXT
FROM indexes
INTO @tablename, @objectid, @indexid, @frag
END
— Close and deallocate the cursor
CLOSE indexes
DEALLOCATE indexes
— Delete the temporary table
DROP TABLE #fraglist
GO

4) Other script that should be run regularly

  • SLServerRestartSp – This stored procedure runs whenever the database server is
    restarted (since no one is logged in at that time) and performs general cleanup.
  • PurgeNextKeySp – Run this stored procedure to clean up the NextKeys table.
    NextKey records are inserted, never updated to get concurrency. This stored
    procedure cleans out the extra rows. DO NOT run this utility while others are using the
    system. The utility will lock users out, but you should log everyone out of the system
    before running this utility.

5) Scripts that can be used to return information related to performance

  • sp_who and sp_who2 – The stored procedure sp_who shows what SPID is blocked;
    sp_who2 shows who is blocking.
  • sp_helpindex (table_name) – Gives index information on a table.
  • DBCC OPENTRAN – Determines whether an open transaction exists within the log.
  • DBCC INPUTBUFFER (SPID) – Displays the last statement sent from a client to SQL
    Server.
  • dbcc showcontig (table_name) – This would show fragmentation information for a table.

How To Cancel Reports In Syteline 7 and 8

October 15th, 2011 No comments

There is no simple way for reports to be cancelled from the client in Syteline 7 and 8. The Cancel button for Print Previews only kills the client part of a Preview. The background task continues to run on the TaskMan machine (The TaskMan machine is typically the Utility Server where the TaskMan process is running.)

There is only one way to kill an individual report. When TaskMan starts a report or an EXE it fills in the Process ID field on the Background Task History form with the Windows Process ID. Log on to the TaskMan machine with the same account TaskMan runs under (or an Administrative account). Bring up the Windows Task Manager. On the Processes tab, select the PID. The Image Name will be RunReport (RunReport.exe) for all reports. Click the End Process button.

If the report is running a stored procedure, simply killing the RunReport process on the Utility Server will not kill the SQL process running within SQL Server. However, identifying this process is more complex. There are generally two main approaches.

1) The simple approach is to stop and re-start the MSSQLSERVER service under Administrative Tools on the SQL Server Box. Or simply re-boot the SQL Server box. However, these approaches will stop all databases and would disrupt business. So they are only appropriate after normal business hours or on a test system. Additionally, once the databases are running again, you would need to re-boot the Utility Server in order for it to properly re-connnect.

2) The more specific, less disruptive approach is most complex. You would need to go into Enterprise Manager, expand the Management folder, expand Current Activity and select Process Info. You would then sort the processes by database so you can reduce the number of processes to examine. You would then right-click on each process in that group, look at the properties and attempt to identify the stored procedure associated with the cancelled report. Most likely, you would only be able to make an educated guess as to what that stored procedure might be based on parts of its name sounding related to the type of report that was killed or cancelled. Once you have identified the process, you can then right-click on it and select Kill Process.

3) The following recommendations may assist with getting the information required to kill the SQL server process associated with the ‘bad’ report.

Firstly, log into Syteline and open the Background Task History form and review recent tasks that are currently in a Running status. For each running task, review the parameter detail information searching for the report or utility that was submitted with no Starting and/or Ending data parameters. Parameters are not labeled, so you may need to look at the Report screen to see what options are available and compare them to the parameters listed in the Background Task History form.

Once you know the Syteline report which is suspected of consuming SQL server resources, open Query Analyzer on your SQL Server, select the App database from which the report was submitted, and run the following query:

SELECT scn.ContextName, scn.ProcessID, ci.UserName
FROM SessionContextNames scn (readuncommitted)
LEFT OUTER JOIN ConnectionInformation ci (readuncommitted)
ON scn.SessionID = ci.ConnectionID
WHERE ci.ConnectionID IS NOT NULL


The above query will return a list of SQL server processes and the associated Syteline information. The column ContextName should return the Syteline form that initiated the process. Search the list of displayed ContextName records for the report which you identified from the Background Task History form. Identify the specific process associated with the desired form and User, and note that ProcessID.

You can then kill the process by running the following in Query Analyzer:

kill spid

where spid would be substituted with the ProcessID value returned in the query you ran. For example, ‘kill 109’.

Please note that killing the process will rollback the transaction so if it has been running for some time, it may take some time for SQL to rollback the transaction and for SQL server resources to return to normal usage levels.