Handle database Journal transaction table with sales and purchase and bank transaction - sql

I create a journal transaction table like this:
CREATE TABLE [dbo].[Finance_Journal_header]
(
[ID] [NVARCHAR](60) NOT NULL,
[Header_number] [INT] NOT NULL,
[Header_date] [DATETIME] NOT NULL,
[nots] [NVARCHAR](4000) NULL,
[UserID] [NVARCHAR](60)NOT NULL,
[isdelete] [BIT] NOT NULL,
[begin_Date] [DATETIME] NOT NULL,
[Company_ID] [NVARCHAR](60) NOT NULL,
[Last_update] [DATETIME] NULL
)
CREATE TABLE [dbo].[Finance_Journal_details]
(
[ID] [NVARCHAR](60) NOT NULL,
[Header_ID] [NVARCHAR](60) NOT NULL,
[Account_code] [NVARCHAR](60) NOT NULL,
[sr] [INT] NOT NULL,
[nots] [NVARCHAR](4000) NULL,
[Debit_value] [NUMERIC](14, 3)NOT NULL,
[Credit_Value] [NUMERIC](14, 3) NOT NULL,
[UserID] [NVARCHAR](60) NOT NULL,
[isdelete] [BIT] NULL,
[begin_Date] [DATETIME] NOT NULL,
[Company_ID] [NVARCHAR](60) NOT NULL,
[Cost_center] [NVARCHAR](60)NOT NULL,
[related_doc] [INT] NOT NULL,
[Exchange_Rate] [DECIMAL](18, 2)NOT NULL,
[Currency_name] [NVARCHAR](60) NOT NULL,
[Last_update] [DATETIME] NULL
)
I have some other tables for Modules transaction like sales, purchase, bank and treasury transaction
How I can link other modules transaction with GL Journal items?
I have two possible solutions:
Create a general view do union select to join any transaction like journal items
Fire a trigger to journal items table details in update with any modules change in any table insert or update or delete
What is the best way to do that?

Related

Brent Ozar's SQL Check Scripts - Memory/CPU/IO Concerns?

How careful do I need to be using Brent Ozar's free SQL health check scripts on a SQL Server 2016 production machine that's very full and very busy already? Has anyone run into memory, CPU or I/O issues running any of the following? Thanks for any feedback.
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzQueryStore
sp_BlitzWho
sp_WhoIsActive (Adam Machanic)
I would not be without it. We have Redgate and I use Brents tools more often.
Our database is 3 Tb and has approx. 1500 queries per second and have never experienced any problems.
Made a custom sp_BlitzWho_Ext which relys on the sp_BlitzWho.
It takes the result of sp_BlitzWho. Puts it in a temp table so I can add a filter. Also cursors are identified and converted so you can see the actual query.
The SQL for dropping the plan_cache of each of them are there - so whenever we get a dumb plan its easy to find and drop the right one.
It now only takes 5 seconds to identify the culprit and get the plan dropped.
First I created a Function to get the query text from the Cursor
create function [dbo].[CursorQuery]
(
#session_id int
) returns nvarchar(255)
as
begin
declare #ret nvarchar(255) = null
SELECT #ret = t.text
FROM sys.dm_exec_cursors (#session_id) c
LEFT JOIN sys.dm_exec_sessions AS es ON c.session_id = es.session_id
CROSS APPLY sys.dm_exec_sql_text (c.sql_handle) t
return #ret
end
Then the stored procedure
CREATE PROCEDURE [dbo].[sp_BlitzWho_Ext]
AS
BEGIN
CREATE TABLE #BlitzWhoResult
(
[run_date] VARCHAR(255),
[elapsed_time] [varchar](41) NULL,
[session_id] [smallint] NOT NULL,
[database_name] [nvarchar](128) NULL,
[query_text] [nvarchar](max) NULL,
[query_plan] [xml] NULL,
[live_query_plan] [xml] NULL,
[query_cost] [float] NULL,
[status] [nvarchar](30) NOT NULL,
[wait_info] [nvarchar](max) NULL,
[top_session_waits] [nvarchar](max) NULL,
[blocking_session_id] [smallint] NULL,
[open_transaction_count] [int] NULL,
[is_implicit_transaction] [int] NOT NULL,
[nt_domain] [nvarchar](128) NULL,
[host_name] [nvarchar](128) NULL,
[login_name] [nvarchar](128) NOT NULL,
[nt_user_name] [nvarchar](128) NULL,
[program_name] [nvarchar](128) NULL,
[fix_parameter_sniffing] [nvarchar](150) NULL,
[client_interface_name] [nvarchar](32) NULL,
[login_time] [datetime] NOT NULL,
[start_time] [datetime] NULL,
[request_time] [datetime] NULL,
[request_cpu_time] [int] NULL,
[request_logical_reads] [bigint] NULL,
[request_writes] [bigint] NULL,
[request_physical_reads] [bigint] NULL,
[session_cpu] [int] NOT NULL,
[session_logical_reads] [bigint] NOT NULL,
[session_physical_reads] [bigint] NOT NULL,
[session_writes] [bigint] NOT NULL,
[tempdb_allocations_mb] [decimal](38, 2) NULL,
[memory_usage] [int] NOT NULL,
[estimated_completion_time] [bigint] NULL,
[percent_complete] [real] NULL,
[deadlock_priority] [int] NULL,
[transaction_isolation_level] [varchar](33) NOT NULL,
[degree_of_parallelism] [smallint] NULL,
[last_dop] [bigint] NULL,
[min_dop] [bigint] NULL,
[max_dop] [bigint] NULL,
[last_grant_kb] [bigint] NULL,
[min_grant_kb] [bigint] NULL,
[max_grant_kb] [bigint] NULL,
[last_used_grant_kb] [bigint] NULL,
[min_used_grant_kb] [bigint] NULL,
[max_used_grant_kb] [bigint] NULL,
[last_ideal_grant_kb] [bigint] NULL,
[min_ideal_grant_kb] [bigint] NULL,
[max_ideal_grant_kb] [bigint] NULL,
[last_reserved_threads] [bigint] NULL,
[min_reserved_threads] [bigint] NULL,
[max_reserved_threads] [bigint] NULL,
[last_used_threads] [bigint] NULL,
[min_used_threads] [bigint] NULL,
[max_used_threads] [bigint] NULL,
[grant_time] [varchar](20) NULL,
[requested_memory_kb] [bigint] NULL,
[grant_memory_kb] [bigint] NULL,
[is_request_granted] [varchar](39) NOT NULL,
[required_memory_kb] [bigint] NULL,
[query_memory_grant_used_memory_kb] [bigint] NULL,
[ideal_memory_kb] [bigint] NULL,
[is_small] [bit] NULL,
[timeout_sec] [int] NULL,
[resource_semaphore_id] [smallint] NULL,
[wait_order] [varchar](20) NULL,
[wait_time_ms] [varchar](20) NULL,
[next_candidate_for_memory_grant] [varchar](3) NOT NULL,
[target_memory_kb] [bigint] NULL,
[max_target_memory_kb] [varchar](30) NULL,
[total_memory_kb] [bigint] NULL,
[available_memory_kb] [bigint] NULL,
[granted_memory_kb] [bigint] NULL,
[query_resource_semaphore_used_memory_kb] [bigint] NULL,
[grantee_count] [int] NULL,
[waiter_count] [int] NULL,
[timeout_error_count] [bigint] NULL,
[forced_grant_count] [varchar](30) NULL,
[workload_group_name] [sysname] NULL,
[resource_pool_name] [sysname] NULL,
[context_info] [varchar](128) NULL,
[query_hash] [binary](8) NULL,
[query_plan_hash] [binary](8) NULL,
[sql_handle] [varbinary] (64) NULL,
[plan_handle] [varbinary] (64) NULL,
[statement_start_offset] INT NULL,
[statement_end_offset] INT NULL
)
INSERT INTO #BlitzWhoResult
EXEC [dbo].[sp_BlitzWho] #ShowSleepingSPIDs = 1, #ExpertMode = 1, #MinElapsedSeconds = 1
SELECT [program_name],
[session_id],
CASE WHEN [query_text] LIKE 'FETCH API_CURSOR%'
THEN CursorQuery(session_id)
ELSE query_text
END AS [query_text],
[query_plan],
[fix_parameter_sniffing] AS [drop_cached_plan_sql],
[status],
[wait_info],
[login_name]
from #BlitzWhoResult
where database_name = 'PUT_YOUR_DATABASENAME_HERE' -- and... add more filters?
DROP TABLE #BlitzWhoResult
END
So.. I really enjoy Brents tool as well as his videos and sense of humour

Mssql old table to new table different data types and empties

I have a new table I created for a membership application for a local club, anyway there existing software stored info in a DBF file I can import this into mssql as a table that's no trouble I am just stuck on merging the old data into the new table.
This is the old Table Structure (From DBF imported into mssql)
[NUMBER] [int] NULL,
[LASTNAME] [char](30) NULL,
[FIRSTNAME] [char](20) NULL,
[TITLE] [char](5) NULL,
[SALUTATION] [char](25) NULL,
[ADD1] [char](30) NULL,
[ADD2] [char](30) NULL,
[ADD3] [char](30) NULL,
[TOWN] [char](30) NULL,
[COUNTY] [char](30) NULL,
[POSTCODE] [char](8) NULL,
[TELEPHONE] [char](30) NULL,
[TYPE] [char](1) NULL,
[PAID] [char](1) NULL,
[COMMITTEE] [char](30) NULL,
[WARNINGS] [int] NULL,
[MONTHDRAW] [int] NULL,
[WOMANS] [char](1) NULL,
[SENIORCIT] [char](1) NULL,
[DOB] [datetime] NULL,
[AMOUNTCLUB] [decimal](6, 2) NULL,
[DATEPAY] [datetime] NULL,
[AMOUNTBRAN] [decimal](6, 2) NULL,
[AMOUNTDUE] [decimal](6, 2) NULL
This is the new Table:
[MemberID] [nvarchar](10) NOT NULL,
[Title] [nvarchar](10) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[Surname] [nvarchar](50) NOT NULL,
[HouseNumber] [nvarchar](25) NULL,
[Street] [nvarchar](25) NULL,
[City] [nvarchar](25) NULL,
[County] [nvarchar](25) NULL,
[Postcode] [nvarchar](10) NULL,
[TelephoneNumber] [nvarchar](15) NULL,
[MobileNumber] [nvarchar](15) NULL,
[EmailAddress] [nvarchar](50) NULL,
[DOB] [date] NULL,
[Age] [nvarchar](10) NULL,
[SeniorCitizen] [nvarchar](5) NULL,
[Warnings] [nvarchar](50) NULL,
[MembershipCategory] [nvarchar](20) NULL,
[ServiceBranch] [nvarchar](20) NULL,
[Paid] [nvarchar](10) NULL,
[ToPay] [float] NULL,
[DatePaidIn] [date] NULL,
[Entry] [tinyint] NULL,
[FOB] [nvarchar](10) NULL,
[JoinDate] [date] NULL,
[SubscriptionYear] [date] NULL,
[TotalPaid] [float] NULL,
I am writing the insert like;
INSERT INTO [dbo].[MemberDetails]
([MemberID],[Title],[FirstName],[Surname],[HouseNumber],[Street],[City],[County],[Postcode],[TelephoneNumber],[MobileNumber],[EmailAddress],[DOB],[Age],[SeniorCitizen],[Warnings],[MembershipCategory],[ServiceBranch],[Paid],[ToPay],[DatePaidIn],[Entry],[FOB],[JoinDate],[SubscriptionYear],[TotalPaid])
SELECT [NUMBER], [TITLE], [FIRSTNAME], [LASTNAME], [ADD1], [ADD2], [TOWN], [COUNTY], [POSTCODE], [TELEPHONE]
FROM [dbo].[MEMBERS]
GO
I got as far as that column then realized "how do I do empty values as no one in the old table had a mobile record?" also do I need to do Select AS "new column name" for the old table values?
Suppose you go from OldTable to NewTable, adding an answer column to the original question column:
insert NewTable
(question, answer)
select question
, '42' -- Specify a literal or default value
from OldTable
You can also omit the new column from the insert list:
insert NewTable
(question)
select question
from OldTable
This will copy the question column and put the default value null in the answer column.
You do not have to use aliases in the select list. It's strictly order based. This would work fine:
insert NewTable
(question)
select question as CeciNEstPasUnePipe
from OldTable

how to prefix identity column character in msSQL

How can I alter a table's primary identity column to include a letter before the number? I have a table named vendor_master with a primary key VendorID that I would like to store as v1,v2,v3 and so on
CREATE TABLE [dbo].[vendor_master](
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL)
If it's important to you to have the field in your table, try the following:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +CONVERT([varchar](10),[vendorID])) PERSISTED
)
Of course, that will yield you some weird results when sorting, so you might consider padding the data with zeroes to make it a consistent length:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +RIGHT('000000000' + CONVERT([varchar](10),[vendorID]),10)) PERSISTED
)
You can't actually do what you are asking. Anyway, there is no reason to add the same letter to the front of a fields value. Instead add the letter in your SELECT statment:
SELECT CONCAT('v', vendorID) AS VendorIDWithPrefix, Vname, Email, Mobile
FROM vendor_master

SQL server sys.dm_db_index_physical_stats Remote scan in query plan

I have a query in db A which shows the index fragmentation level and recent rebuilt or re-organised status, it cross apply a function B in db C, A and C are on the same instance.
Function B is:
ALTER function [dbo].[B]
(
#db_id int
,#object_id int
,#index_id int
,#partition_number int
,#mode varchar (20)
)
returns #results TABLE (
[database_id] [smallint] NULL,
[object_id] [int] NULL,
[index_id] [int] NULL,
[partition_number] [int] NULL,
[index_type_desc] [nvarchar](60) NULL,
[alloc_unit_type_desc] [nvarchar](60) NULL,
[index_depth] [tinyint] NULL,
[index_level] [tinyint] NULL,
[avg_fragmentation_in_percent] [float] NULL,
[fragment_count] [bigint] NULL,
[avg_fragment_size_in_pages] [float] NULL,
[page_count] [bigint] NULL,
[avg_page_space_used_in_percent] [float] NULL,
[record_count] [bigint] NULL,
[ghost_record_count] [bigint] NULL,
[version_ghost_record_count] [bigint] NULL,
[min_record_size_in_bytes] [int] NULL,
[max_record_size_in_bytes] [int] NULL,
[avg_record_size_in_bytes] [float] NULL,
[forwarded_record_count] [bigint] NULL,
[compressed_page_count] [bigint] NULL
)
begin
insert into #results
select *
from sys.dm_db_index_physical_stats (#db_id, #object_id, #index_id ,#partition_number
,#mode )
return
end
This query takes a long time to execute. I read the query plan, the plan contains a "Remote Scan". I don't understand why is that.
Can anyone help?
Thanks,

Auditing trigger - Column name or number of supplied values does not match table definition

I am attempting to create a database trigger capable of creating a snapshot of a 'Transactions' table and storing it in an 'Audit' table along with information pertaining to the date of the inserting, updating or deleting of any rows of data.
Apologies in advance, but I'm very much a novice at this kinda stuff!
As it stands, my trigger is as follows:
create trigger AuditTransactions
on dbo.Transactions
after insert, update, delete
as
if exists(select * from inserted)
begin
if exists(select * from deleted)
begin
-- this is for an update
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
end
-- this is just for an insert
insert into Audit
select *, getdate() as CreateDate
from inserted
end
else
begin
-- this is just for a delete
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
end
go
And my audit table appears as follows:
CREATE TABLE [dbo].[Audit](
[TransactionId] [int] NOT NULL,
[InvoiceNumber] [nvarchar](1) NULL,
[InvoiceType] [nvarchar](1) NULL,
[InvoiceIssueDate] [datetime] NULL,
[InvoiceTotalexclVat] [nvarchar](1) NULL,
[InvoiceTotalVat] [numeric](18, 0) NULL,
[InvoiceDiscount] [numeric](18, 0) NULL,
[InvoiceTotalPayable] [numeric](18, 0) NULL,
[AccountCode] [nvarchar](1) NULL,
[Reference1] [nvarchar](1) NULL,
[Reference2] [nvarchar](1) NULL,
[Reference3] [nvarchar](1) NULL,
[Level1CustomOrg] [nvarchar](1) NULL,
[Level2CustomOrg] [nvarchar](1) NULL,
[Level3CustomOrg] [nvarchar](1) NULL,
[Level4CustomOrg] [nvarchar](1) NULL,
[ScanLocation] [nvarchar](1) NULL,
[ScanDateTime] [datetime] NULL,
[CaptureInkjetId] [nvarchar](1) NULL,
[CaptureBatchId] [nvarchar](1) NULL,
[CaptureDateTime] [datetime] NULL,
[InputSource] [nvarchar](1) NULL,
[CurrencyCode] [nvarchar](1) NULL,
[DebitCredit] [nvarchar](1) NULL,
[OrderNumberHeader] [nvarchar](1) NULL,
[SupplierName] [nvarchar](1) NULL,
[BancPaySupplierId] [nvarchar](1) NULL,
[SupplierIDERP] [nvarchar](1) NULL,
[PaymentDate] [datetime] NULL,
[DeliveryDate] [datetime] NULL,
[CustomRef1] [nvarchar](1) NULL,
[CustomRef2] [nvarchar](1) NULL,
[CustomRef3] [nvarchar](1) NULL,
[CustomRef4] [nvarchar](1) NULL,
[CustomRef5] [nvarchar](1) NULL,
[CustomRef6] [nvarchar](1) NULL,
[CustomRef7] [nvarchar](1) NULL,
[CustomRef8] [nvarchar](1) NULL,
[CustomRef9] [nvarchar](1) NULL,
[CustomRef10] [nvarchar](1) NULL,
[CustomRef11] [nvarchar](1) NULL,
[CustomRef12] [nvarchar](1) NULL,
[CustomRef13] [nvarchar](1) NULL,
[CustomRef14] [nvarchar](1) NULL,
[CustomRef15] [nvarchar](1) NULL,
[CustomAmount1] [numeric](18, 0) NULL,
[CustomAmount2] [numeric](18, 0) NULL,
[CustomAmount3] [numeric](18, 0) NULL,
[CustomAmount4] [numeric](18, 0) NULL,
[CustomAmount5] [numeric](18, 0) NULL,
[CustomDate1] [datetime] NULL,
[CustomDate2] [datetime] NULL,
[Country1] [nvarchar](1) NULL,
[Country2] [nvarchar](1) NULL,
[Country3] [nvarchar](1) NULL,
[Country4] [nvarchar](1) NULL,
[Country5] [nvarchar](1) NULL,
[Country6] [nvarchar](1) NULL,
[Country7] [nvarchar](1) NULL,
[Country8] [nvarchar](1) NULL,
[Country9] [nvarchar](1) NULL,
[Country10] [nvarchar](1) NULL,
[CheckedOut] [bit] NULL,
[CheckedOutDate] [datetime] NULL,
[BlobUrl] [nvarchar](1) NULL,
[GLCode] [nvarchar](1) NULL,
[RejectReason] [nvarchar](1) NULL,
[RejectComment] [nvarchar](1) NULL,
[ReferMessage] [nvarchar](1) NULL,
[PaymentTerms] [nvarchar](1) NULL,
[CheckedOutByUserId] [int] NULL,
[LastUpdatedByUserId] [int] NULL,
[TransactionFormatTypeId] [int] NULL,
[RequestOriginalStatusTypeId] [int] NULL,
[GLCodeComment] [nvarchar](1) NULL,
[SenderOrganizationId] [int] NULL,
[ReceiverOrganizationId] [int] NULL,
[TransactionStatusTypeId] [int] NULL,
[TransactionTypeId] [int] NULL,
[OrganizationId] [int] NULL,
[OrganizationId1] [int] NULL,
[CreateDate] [datetime] NOT NULL,
[DeleteDate] [datetime] NULL
) ON [PRIMARY]
GO
When attempting to execute the query for the trigger I am getting the following error message:
Msg 213, Level 16, State 1, Procedure AuditTransactions, Line 17
Column name or number of supplied values does not match table definition.
This appears to be the 'insert into Audit' command, but I have no idea what to do from here!
Any help will be hugely appreciated, thanks in advance!
INSERT seems to be rather poorly documented. For the VALUES() element, it states the following:
If the values in the Value list are not in the same order as the columns in the table or do not have a value for each column in the table, column_list must be used to explicitly specify the column that stores each incoming value.
(Emphasis added)
However, it is my understanding and belief that the same constraint applies, no matter what the source of values/rows are - that unless you exactly match all columns in the table, you need to provide the column_list.
Now, for your instance, it may be easier if you just provide a value for every column in the table:
insert into Audit
select *, getdate() as CreateDate,null as DeleteDate
from inserted
Now, my other observation is that all this mucking about with conditional control flow is rather pointless - an insert of 0 rows will have no effect, and an update using in against an empty table will similarly have no effect. So I'd just have:
create trigger AuditTransactions
on dbo.Transactions
after insert, update, delete
as
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
insert into Audit
select *, getdate() as CreateDate,null as DeleteDate
from inserted
insert into Audit
select *, getdate() as CreateDate, null
from inserted
Your "audit" table has more columns than you're inserting (the deleted date); you need to either name all the columns, or insert a null.
Stylistically, naming the columns is better - it makes it clear what goes where, and avoid bugs when you add new columns.