Archive

Archive for the ‘SQL’ Category

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’

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]
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

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]
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

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]
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())

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]

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.
[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]

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.

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]

Truncate SQL Log File

October 15th, 2011 No comments

Use the following script to shrink/truncate SQL database log file

USE [Database_Name]
GO
ALTER DATABASE [Database_Name] SET RECOVERY SIMPLE WITH NO_WAIT
DBCC SHRINKFILE(DB_Log_File_Logical_Name, 1)
ALTER DATABASE [Database_Name] SET RECOVERY FULL WITH NO_WAIT
GO

Use the following script to check the file size.

USE [Database_Name]
GO

select name,  size from sys.database_files

 

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]
Categories: Development, SQL Tags: ,

Exclusive Access can’t obtained error when restoring SQL database

October 15th, 2011 No comments

When you try restoring a SQL database, you may get an error message saying “Exclusive access can’t obtained, database is in use”.   First, of course, stop all Syteline service, like IDO, Taskman.  If it still doesn’t work, try the below to set it to single user mode

Use Master

Alter Database Database_Name  SET SINGLE_USER With ROLLBACK IMMEDIATE

You may run Exec sp_who2 to see the user connection to database.

If this still doesn’t work, try detach/reattach the database.

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]

How To Convert SQL Server 2008 Database To SQL Server 2005?

July 11th, 2011 No comments

Requirements

If you are trying to restore database backup of SQL Server 2008 to SQL Server 2005, you are bound to fail. Database backup of SQL Server 2008 is not compatible backward, you cannot restore it to SQL Server 2005. The following is a solution to convert databases of SQL Server 2008 to 2005

Step by Step Guide

1) Start convert wizard

Open SQL Server Management Studio2008. in ‘Object Explorer’, right click the database that you want to convert. Select ‘Tasks’ > ‘Generate Scripts…’.

Change Hyper-V Default Folders Step 1

2) Next

Click ‘Next’.

Change Hyper-V Default Folders Step 1

3) Select database and objects

Select the database that you want to convert, and check on ‘Scripts all objects in the selected databases

Change Hyper-V Default Folders Step 2

4) Convert Options

Set options:

'Script for Server Version' = 'SQL Server 2005'
'Script Data' = 'True'
'Scirpt Database Create' = 'True'
    

Change Hyper-V Default Folders Step 2

5) Output Option

Select option ‘Script to file’, ‘Single file’ and ‘Unicode text’.

Change Hyper-V Default Folders Step 1

6) ‘Finish’

View summary and click ‘Finish’.

Change Hyper-V Default Folders Step 1

7) Result

Now you got a complete database creation script with data. It can be executed on target database server.

Change Hyper-V Default Folders Step 1

8) Amend Script

Open the generated script in SQL Server Management Studio 2005. Find the following section and amend the path to proper data folder

    CREATE DATABASE [StockTraderDB] ON  PRIMARY 
( NAME = N'StockTraderDB', 
FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\StockTraderDB.mdf ,
 SIZE = 4352KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'StockTraderDB_log', 
FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\StockTraderDB_log.LDF',
 SIZE = 6272KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
9) Execute the Script

When finished, You should get converted database of SQL Server 2005

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]
Categories: SQL Tags:

Copy the User/Module Authorization from one Syteline DB to another DB

January 17th, 2011 No comments

If you have hundreds users, manually rebuilding the User/Module Authorization will be painful.  The below query will copy over the User/Module Authorization from source DB to target DB.  Just run it against your target DB.

insert  modulemembers (objecttype, objectname, modulename, originalmodulename, modulememberspec)
select objecttype, objectname, modulename, originalmodulename, modulememberspec
from [Your_Source_DB_name].[dbo].[modulemembers]
where objectname like ‘OS_%’

[del.icio.us] [Facebook] [Google] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]