mardi 30 juin 2015

How to get month number in sql by passing the week number

This is my function as below

CREATE FUNCTION  getmonth
(        

 @startdate  datetime,@Week int
)        
RETURNS  int        
AS        
BEGIN                      
 declare @year int,@Month int;              
 declare @sdate  datetime=@startdate;       
 set @year= year(CAST(@startdate as date));  
 set @sdate = DATEADD(wk, DATEDIFF(wk, 6,  '1/1/' + CAST( @year as varchar(4)) ) + (@Week-1) ,1);           
  SET @Month = month( @sdate);              
 return @month        

END        

I Just want this function to return the month number when we pass a week number of the year and week start date of year.

Week should be start on Sunday and ends at Saturday.

Example

For Year 2015,Week start date is 12/28/2014.When we pass week number it should return the month number of year 2015.

Stored procdure null value convert into zero and can't using order by clause

This query return:

month 2014 2015  

apr   null  2000

feb   3000  null

dec   null  2000

may   5000  null

How to solve Null value convert into zero and Showing all month by order

This is my query:

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(year(DateOfTransaction)) 
                    from TBL_Transactionmaster
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [Month],' + @cols + ' from 
             (
                SELECT 
            left(datename(month,DateOfTransaction),3)as [month], year(DateOfTransaction) as [year]
            ,  Amount 
        FROM TBL_Transactionmaster
            ) x
            pivot 
            (
                sum(amount)
                for [year] in (' + @cols + ')
            ) p '

execute(@query)

SQL Server Identity Column Renumbering

I have a table which has a primary key ID column and is set to increment 1 for each new entry, a fairly standard configuration. This table is updated regularly with new records, and is archived once a month to an archive table and then truncated.

Under normal operation the next record to go into the table after truncation would be whatever the next ID value is, ensuring that there is no overlap in IDs between the archive table and the "live" table.

Due to unknown factors, somehow the ID column in the live table "reverted" back to an ID that has already been used. Because this database was designed poorly, now I've got some data integrity issues.

My solution to resolve the issue is to update the ID column for all records in the "live" table so there will be no overlap with the ID's that exist in the "archive" table. Once I update the IDs I will reseed the Identity column so that future records will also not overlap.

My question is not about reseeding the column (using DBCC -- I know how to do this) but about how to go about re-numbering the existing records with new ID values. Should I do this with a looped dynamic SQL query (delete record, insert record), or is there some SQL Server function I am unaware of that can automatically renumber the ID column?

MSSQL - How to know which SP called a function in real time

I need to know which procedure called, in real time, my function.

I need to store a log every time that my functions is called, and in that log I need to know the name of the SP that called it.

I found this:

select so.name 'Object Name', so2.name 'Dependent On', sd.*
from sys.sysdepends sd
join sys.objects so on so.object_id = sd.id
join sys.objects so2 on so2.object_id = sd.depid
where so2.name = 'FUNCTION_NAME'

But, this code returns the dependencies, I mean, all the SPs that were compiled calling the function BUT what I really need to know it the procedure that is actually, in that particular call, calling the function so I can store it in a Log Table.

Thanks!

lundi 29 juin 2015

MS SQL 2005 Auto Increment Error

So, I have tried to create a table inside my database 'Test',

CREATE TABLE TestTbl(
id INT IDENTITY(1,1),
Agent_id VARCHAR(255) NOT NULL
)

After it was created, I tried to add 2 values for the agent via php, but the result is this:

id | Agent_id
0     8080
0     8081

It does not auto increment, even if I set 'id' as a Primary key, still the problem occurs, anyone knows how to solve this problem?

Here is my insert statement in php, nevermind the $conn, because it works, it is for my sql connection

 if(isset($_POST['agentid'])){
    $agent = $_POST['agentid'];
    $query = "SELECT * FROM [Test].[dbo].[TestTbl] WHERE [Agent_id] = '$agent'";
    $result = sqlsrv_query($conn,$query);
      if(sqlsrv_has_rows($result) !=0){
    echo "ID EXISTS";
       }else{
    $sql = "SET INDENTITY_INSERT TestTbl ON
    INSERT INTO [Test].[dbo].[TestTbl]
    ([id],[Agent_id]) VALUES ('','$agent')
    SET IDENTITY_INSERT TestTbl OFF";
    echo "Added";
    }}

Installing SQL express 2005 in server having SQL server 2008 R2 installed

Am trying to installing SQL2005 express edition in the windows server 2008 where we already have the SQL server 2008 R2 express edition installed in it.

Will that be possible?

Query is giving invalid column error

I have a query which is giving me error as

Column 'designation' does not belong to table Table.

Here is my query:-

Select  upper(ra1user.first_name +  ' ' + ra1user.last_name)  RA1_Name, " +
                       "ra1user.email As RA1_Email_ID,  upper(ra2user.first_name + ' ' + ra2user.last_name) [RA2 Name], " +
                       "ra2user.email As RA2_Email_ID, upper(Emp_name) empName, " +
                       "um.email As empEmail_ID, upper(empDesignation) empDesignation, " + 
                       "(select CONVERT(VARCHAR(10),dateadd(mm,1,DATEADD(dd,-(DAY(getdate())-1),getdate())),101)) " +
                       "as empConfirmation_Date  , " +
                       "convert(varchar(10), em.date_of_Joining, 103) as date_of_Joining " +
                      "from    emp_mst em " +
                       "join user_mst um on um.employee_mkey = em.mkey  " +
                       "left join user_mst ra1user on ra1user.employee_mkey = em.reporting_to  " +
                       "left join user_mst ra2user on ra2user.employee_mkey = em.reporting_to2  " +
                       "join type_mst_a desig on em.new_design_mkey=desig.master_mkey " +
                        "where  em.emp_card_no="

VIEW

ALTER view [dbo].[XXACL_ERP_EMP_Confirmation_View] as  select
*  

from ( select distinct comp.company_name Company_Name, case when e.comp_mkey!=e.on_Deput_comp_mkey then Dcomp.company_name else '' end Deputed_Company_Name , 'NA' [Company Code], e.emp_card_no [Emp_Card_No], 'NA' Title, e.emp_name [Employee_Name], usr.first_name [First_Name], replace(d1.type_desc, '', '') Designation, grade.type_desc Grade , replace(isnull(b1.type_desc, '--NA--'), '', '') as 'Department' , isnull(b2.type_desc, '--NA--') as 'Sub Department' , isnull(hub.type_desc, '--NA--') as Hub_Name , 'NA' Location , 'NA' City , 'NA' [State Name] , case when e.emp_type='E' then 'HO-Employee' when e.emp_type='T' then 'Temporary'
when e.emp_type='C' then 'Consultant'
when e.emp_type='S' then 'Site-Employee' else 'Temporary-OutSource' end [Emp_Type] , convert(datetime, e.date_of_joining, 103) Date_of_Joining , convert(datetime, e.dt_of_birth, 103) DOB , ctc.final_ctc_amt [Fixed CTC P.A] , ctc.variance_amt [Variable CTC P.A] , ctc.Anu_ctc_amt Total_CTC_PA , dbo.fn_spellNumber(cast(cast(ctc.Anu_ctc_amt as numeric(18, 0)) as varchar), 'UK', '0') [CTC_in_Word] , convert(datetime, ctc.pay_slip_eff_date, 103) [Last Increment Date] , case when (select count() from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no
and ra1_mkey is not null)>0 then (select top 1 emp_mst.emp_name as 'RA1 Name' from emp_mst, p_emp_confirmation_hdr
where p_emp_confirmation_hdr.ra1_mkey=emp_mst.mkey and p_emp_confirmation_hdr.emp_card_no=e.emp_card_no)
else s1.emp_name end as 'RA1 Name', case when (select count(
) from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no
and ra2_mkey is not null)>0 then (select top 1 emp_mst.emp_name as 'RA2 Name' from emp_mst, p_emp_confirmation_hdr
where p_emp_confirmation_hdr.ra2_mkey=emp_mst.mkey and p_emp_confirmation_hdr.emp_card_no=e.emp_card_no)
else s2.emp_name end as 'RA2 Name', --, s1.emp_name as 'RA1 Name', --isnull(s2.emp_name, '--NA--') as 'RA2 Name' 'NA' 'Functional Head Name' , 'NA' [Probation Period], CASE WHEN (select count() from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no)>0 then (select top 1 confirmation_date from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no)
else CONVERT(VARCHAR(25), dateadd(mm, 1, DATEADD(dd, -(DAY(getdate())-1), getdate())), 103) end AS Confirmation_Date --case when convert(varchar, e.date_of_confirmation, 103)='01/01/1900' then null else --convert(datetime, e.date_of_confirmation, 103) end Confirmation_Date , 'NA' 'Confirmation Remarks' , case when e.status='A' then 'Active'
when e.status='S' then 'Active'
when e.status='F' then 'Full and Final'
when e.status='R' then 'Resign' else 'NA' end [Employee Status] , 'NA' [Notice Period Term] , case when e.resig_date='1900-01-01 00:00:00.000' then null else convert(datetime, e.resig_date, 103) end [Resigned Date] , 'NA' 'Resignation Received HR' , case when e.dt_of_leave='1900-01-01 00:00:00.000' then null
else convert(datetime, e.dt_of_leave, 103) end [Last Working Date] , e.Reason_of_resignation [Reason for Leaving] , 'NA' [Sourced Through] , 'NA' 'Replacement For' , case when e.marital_status='M' then 'Married' when e.marital_status='U' then 'UnMarried' else '--NA--'
end [Marital Status] , 'NA' [Qualification Category] , dbo.StringConcat(( isnull((select isnull(education, '') +'--'+ isnull(edu.remarks , '')
from p_Emp_Education edu
join p_education_mst edumst on edu.education_mkey=edumst.mkey
where edu.mkey=e.mkey
and Entry_Srno=1
order by entry_srno for xml raw, elements), 'NA'))) 'Highest Qualification' , 'NA' Graduation , 'NA'[GradYear Passed] , 'NA' [Post Graduation] , 'NA' [Post Grad Year Passed] , ad.add_1 Address_Line1 , ad.add_2 Address_Line2 , c.city_name as Address_City , ad.pincode as 'PinCode' , stmst.State_name Address_State , Residence_No 'Telephone No.' , e.mobile_no 'Mobile No.' , e.email_id_official [EmailId Official] , e.email_id_personal 'EmailId Personal' , e.pan_no 'PAN CARD' , isnull(e.pf_no, '--NA--') as 'PF_No' , isnull(e.ESIC_No, '--NA--') as 'ESIC_No' , isnull(e.passport_no, '--NA--') as 'Passport_No' , e.Work_Exp as 'Previous Experience Year' , fam.Member_Name as 'Family Details 1 Name' , r.relation 'Family Details 1 Relation' , isnull(convert(varchar, fam.DOB, 103), 'null') as 'Family Details 1 DOB' , fam1.Member_Name as 'Family Details 2 Name' , r1.relation 'Family Details 2 Relation' , isnull(convert(varchar, fam1.DOB, 103), 'null') as 'Family Details 2 DOB' , fam2.Member_Name as 'Family Details 3 Name' , r2.relation 'Family Details 3 Relation' , isnull(convert(varchar, fam2.DOB, 103), 'null') as 'Family Details 3 DOB' , fam3.Member_Name as 'Family Details 4 Name' , r3.relation 'Family Details 4 Relation' , isnull(convert(varchar, fam3.DOB, 103), 'null') as 'Family Details 4 DOB' , e.bld_grp 'Blood Group' --, bld.type_desc blood_type , 'NA' 'Background Verif Doc' --, case when Medical_Fit='Y' then 'Yes' else 'No' end Medical_Fitness , 'NA' 'Medical Fitness' , 'NA' 'Medical Fitness Remark' , 'NA' 'Graphology Test' , 'NA' 'Bank A/C status' , bank.bank_name [Bank Name] , e.citybank_acc_no 'Bank Account Number' , case when e.on_Deput_comp_mkey>0 then e.on_Deput_comp_mkey else e.comp_mkey
end comp_mkey , e.new_design_mkey , e.New_Dept_mkey , e.ctc_hdr_mkey , e.status emp_status1 , e.mkey emp_mkey , e.subdept_mkey , e.department_mkey , e.mkey, CASE WHEN (select count(
) from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no)>0 then (select top 1 confirmation_date as 'confirmation_Due_On' from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no) else CONVERT(VARCHAR(25), dateadd(mm, 1, DATEADD(dd, -(DAY(getdate())-1), getdate())), 103) end as 'confirmation_Due_On' -- e.confirmation_due_on , CASE WHEN (select count() from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no)>0 then (select top 1 PROBATION_PERIOD as 'PROBATION_PERIOD' from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no) else (select datediff(d, e.dt_of_join, CONVERT(VARCHAR(25), dateadd(mm, 1, DATEADD(dd, -(DAY(getdate())-1), getdate())), 101))/30) END as Probation_Period --, e.Probation_Period , e.wages_type , e.reporting_to , e.reporting_to2 , CASE WHEN (select count() from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no)>0 then (select top 1 LEAVE_TAKEN_PROB_PER as 'Absent_Count' from p_emp_confirmation_hdr where emp_card_no=e.emp_card_no) else (select erplive.dbo.AbsentCount_view(e.emp_card_no)) end as Absent_count --, (select count() from xxacl_ERP_AB_PL_Count_V where emp_card_no = e.emp_card_no) Absent_count , case
when (select count(
) from xxacl_ERP_AB_PL_Count_View where emp_card_no= e.emp_card_no)>7 then dateadd(mm, e.probation_period+1, e.Date_of_Joining)
when day(e.Date_of_Joining)>15 then dateadd(mm, e.probation_period+1, e.Date_of_Joining)
else e.date_of_confirmation
end Confirmation_Date_New , case
when (select isnull(sum(total_day), 0) from xxacl_ERP_AB_PL_Count_View where emp_card_no= e.emp_card_no)>7 --then 'DOC Exteded By 1 month. Reason:- Taken leave='+ Convert(varchar, (select SUM(TOTAL_DAY) from xxacl_ERP_AB_PL_Count_View where emp_card_no = e.emp_card_no))+' which is > 7. Actual DOC='+Convert(Varchar, dateadd(mm, e.probation_period, e.Date_of_Joining), 103)+'' then 'N/A' -- when day(e.Date_of_Joining)>15 -- then 'N/A'-- 'DOC Exteded By 1 month. Reason:- DOJ should be before 15th of month. Actual DOC='+Convert(varchar, dateadd(mm, e.probation_period, e.Date_of_Joining), 103)+''
else 'N/A'
end Remark , case when e.sex='F' then 'Female'
when e.sex='M' then 'Male'
else 'NA' end Gender , ctc.mkey CTC_MKEY , case when e.on_Deput_comp_mkey>0 then Dcomp.add1+' '+Dcomp.add2+ '' +Dcomp.city else comp.add1+' '+comp.add2+ '' +comp.city
end Company_Add , convert( varchar, getdate(), 103) curr_date , case when b1.add_tinfo1='C' then 'Core' else 'Support' end Core_Support , case when e.ctc_hdr_mkey in (213, 214, 215) then 30 else 90 end Prob_period_Letter, isnull(e.func_role_mkey, 0) func_role_mkey --, e.new_design_mkey
from emp_mst e
left join emp_shift_details b on e.emp_card_no=b.emp_card_no
and b.mkey = ( select max(mkey) from emp_shift_details c where b.emp_card_no=c.emp_card_no )
left join emp_mst1 e1 on e.emp_card_no=e1.emp_card_no -- and e.emp_card_no=1216 -- left join user_mst u on e.mkey=u.employee_mkey
left join shift_master s on b.shift_mkey=s.mkey
left join company_mst comp on e.comp_mkey=comp.mkey and comp.fa_year=2008
left join company_mst Dcomp on e.on_Deput_comp_mkey=Dcomp.mkey and Dcomp.fa_year=2008
left join type_mst_a grade on e.ctc_hdr_mkey=grade.add_iinfo1
left join type_mst_a d1 on e.new_design_mkey=d1.master_mkey
left join type_mst_a b1 on e.New_Dept_mkey=b1.master_mkey
left join type_mst_a b2 on e.New_subDept_mkey=b2.master_mkey
left join type_mst_a pw on e.paidweekly_off=pw.type_abbr
left join type_mst_a po on e.weekly_off=po.type_abbr
left join type_mst_a hub on e.Hub_Mkey=hub.master_mkey
left join state_mst st on e1.domicile_mkey=st.mkey and e1.country_of_birth=st.country_mkey and st.add_flag='N'
left join emp_mst s1 on s1.mkey=e.reporting_to
left join emp_mst s2 on s2.mkey=e.reporting_to2
left join ctc_recal_group_hdr ctc on ctc.emp_mkey=e.mkey
and ctc.mkey = ( select max(mkey) from ctc_recal_group_hdr c where e.mkey=c.emp_mkey and delete_flag='N' )
left join emp_address_trl ad on e.mkey=ad.mkey and ad.entry_sr_no=( select max(entry_sr_no) from emp_address_trl where mkey=e.mkey )
left join city_mst as c on ad.city_mkey = c.mkey
left join state_mst stmst
on ad.state_mkey = stmst.mkey
left join p_Emp_Family fam on e.mkey=fam.mkey and fam.entry_srno=1
left join p_relation_mst r on r.mkey=fam.relation_mkey
left join p_Emp_Family fam1 on e.mkey=fam1.mkey and fam1.entry_srno=2
left join p_relation_mst r1 on r1.mkey=fam1.relation_mkey
left join p_Emp_Family fam2 on e.mkey=fam2.mkey and fam2.entry_srno=3
left join p_relation_mst r2 on r2.mkey=fam2.relation_mkey
left join p_Emp_Family fam3 on e.mkey=fam3.mkey and fam3.entry_srno=4
left join p_relation_mst r3 on r3.mkey=fam3.relation_mkey
left join type_mst_a bld on e1.blood_type=bld.master_mkey and bld.type_code='BG'
and bld.delete_flag='N'
left join user_mst usr on e.mkey=usr.employee_mkey
left join p_bank_mst bank on e.bank_code=bank.mkey -- where type_code='PWP'
where 1=1
and e.emp_card_no!=9999 -- and e.emp_card_no not in ( select emp_card_no from P_Emp_Confirmation_Hdr )
and e.emp_card_no in ( 2385 ,2380 ,2377 ,2337 ,2361,2371
)
) aa -- and e.emp_card_no=9999 -- and e.mkey<=1932 -- b.mkey = ( select max(mkey) from emp_shift_details c where b.emp_card_no=c.emp_card_no ) -- and e.emp_card_no=2192 -- and ctc.mkey = ( select max(mkey) from ctc_recal_group_hdr c where e.mkey=c.emp_mkey and delete_flag='N' ) GO

jeudi 25 juin 2015

sqlsrv and param count error

Good Day,

Before anything else, I can successfully connect to my database and I can print out all the data from my table..

This is my problem, I am experiencing a warning and fatal error when I try to do this:

$sql = sqlsrv_query("SELECT [name] FROM [Test].[dbo].[TestTable] WHERE [name] = '$user', $conn);
$rows = sqlsrv_num_rows($conn,$sql);

This is the error that I'm getting,

sqlsrv_query() expects parameter 1 to be resource....Param count and argument count don't match

SQL Server Dynamic Filter

Does anybody know how to create a dynamic search filter without using 'OR' or 'Coalesce' because OR has performance issues and Coalesce doesnt give the correct data

Thanks

mercredi 24 juin 2015

C# error "Could not find Stored procedure" if DB collation is not “SQL_Latin1_General_CP1_CI_AS”

This is the situation that I encountered:


A) C# code: execute stored procedure "Check_Data"

  • I would like to state that there is nothing wrong with my C# code here as it is as basic as it can get, and it is also double-checked by me and my co-workers.

B) SQL Server:

  • All DBs are MSSQL2005. Please do not suggest to upgrade them, as this is what my client uses.

  • Please note that all 4 DBs below is created in the exact same way, as well as the stored procedure "Check_Data". The only difference is the collation of each DB.

  • I used user "sa" to connect to all DB to make sure that there is no problem with permission.

  • Instance A: collation “SQL_Latin1_General_CP1_CI_AS”

    • DB 1: collation “SQL_Latin1_General_CP1_CI_AS” => C# code run successful.
    • DB 2: collation “Vietnamese_CI_AS” => C# code has error "Could not find Stored procedure" .
  • Instance B: collation “Vietnamese_CI_AS”

    • DB 1: collation “SQL_Latin1_General_CP1_CI_AS” => C# code run successful.
    • DB 2: collation “Vietnamese_CI_AS” => C# code has error "Could not find Stored procedure" .

So basically, my DB just hate collation “Vietnamese_CI_AS” and refuse to get this stored procedure.

This is the script of "Check_Data":

CREATE PROCEDURE [dbo].[Check_Data]
(   
    @Acc    nvarchar(50),   
    @Status varchar(500) OUTPUT)
AS
BEGIN

if exists (select 1 from tblRequest where Acc=@Acc)

    SET @Status = '1'--have data
else
    SET @Status = '0'--have not data        
END

Could anyone tell me what is wrong with it?

Php 5.6 Driver for Windows Server 2008 R2

Good Day - This is what I am trying to do at the Windows Server 2008 R2 SP1:

  • So I have tried to add the php_sqlsrv_56_ts.dll(from microsoft) at the ext folder of my php inside xampp, and I enabled it at the php.ini file, but if I try to make a simple php script echo phpinfo(); ,sqlsrv does not show up even though I added it.
  • I also tried to do this: extension=C:\xampp\php\ext\php_sqlsrv_56_ts.dll still no luck...
    • If you are wondering, I am using MS SQL 2005
    • Php Version is 5.6

This really breaks my brain because I tried it to my other laptop which has windows 7 OS, and it really works. Everything I have here in my win 7 OS(XAMPP) is also the same as what I have in my Windows Server 2008 R2

Using the result of a subquery in a CASE expression with T-SQL

I'm writing a query with some CASE expressions and it outputs helper-data columns which help me determine whether or not a specific action is required. I would like to know if I can somehow use the result of a subquery as the output without having to perform the same query twice (between WHEN (subquery) THEN and as the result after THEN)

The dummy code below describes what I'm after. Can this be done? I'm querying a MS2005 SQL database.

SELECT   'Hello StackOverflow'
        ,'Thanks for reading this question'
        ,CASE
            WHEN 
                (
                    SELECT count(*)
                    FROM    sometable
                    WHERE   condition = 1
                    AND     somethingelse = 'value'
                ) > 0 THEN
                    -- run the query again to get the number of rows
                    (
                        SELECT count(*)
                        FROM    sometable
                        WHERE   condition = 1
                        AND     somethingelse = 'value'
                    )
            ELSE 0
         END

SELECT   'Hello StackOverflow'
        ,'Thanks for reading this question'
        ,CASE
            WHEN 
                (
                    SELECT count(*)
                    FROM    sometable
                    WHERE   condition = 1
                    AND     somethingelse = 'value'
                ) AS subqry_count > 0 THEN
                    -- use the subqry_count, which fails... "Incorrect syntax near the keyword 'AS'"
                    subqry_count
            ELSE 0
         END

SQL Server 2005: DoMiniDump () encountered error (0x80004005) - Unspecified error

We're running a MSSQL 2005 database and are getting the following output(error?) in our logs:

06/23/2015 21:56:41,Server,Unknown,Process 214:0:42 (0x73b0) Worker 0x0000000BB2CC61A0 appears to be non-yielding on Scheduler 39. Thread creation time: 13079558329722. Approx Thread CPU Used: kernel 0 ms<c/> user 0 ms. Process Utilization 8%. System Idle 91%. Interval: 70169 ms.
06/23/2015 21:56:41,Server,Unknown,DoMiniDump () encountered error (0x80004005) - Unspecified error
06/23/2015 21:56:41,Server,Unknown,External dump process return code 0x20000001.<nl/>External dump process returned no errors.
06/23/2015 21:56:38,Server,Unknown,Stack Signature for the dump is 0x000000000000028A
06/23/2015 21:56:38,Server,Unknown,* *******************************************************************************
06/23/2015 21:56:38,Server,Unknown,*
06/23/2015 21:56:38,Server,Unknown,* Non-yielding Scheduler
06/23/2015 21:56:38,Server,Unknown,*
06/23/2015 21:56:38,Server,Unknown,*   06/23/15 21:56:38 spid 8656
06/23/2015 21:56:38,Server,Unknown,* BEGIN STACK DUMP:
06/23/2015 21:56:38,Server,Unknown,*
06/23/2015 21:56:38,Server,Unknown,* *******************************************************************************
06/23/2015 21:56:38,Server,Unknown,***Unable to get thread context for spid 0
06/23/2015 21:56:38,Server,Unknown,Using 'dbghelp.dll' version '4.0.5'

I can't find much about this on google. There a lot of similar errors, which talk about hanging sql servers and that this might be a user trying to execute a dump that has no permission? I can't find anything about this exact error though.

Could anybody point me in the right direction or know immediately what is causing this?

Note: We've been getting the following error as well, which might have something do with it, but I'm not sure:

06/23/2015 22:22:50,spid23s,Unknown,SQL Server failed to prepare DTC transaction. Failure code: 8522.
06/23/2015 22:22:50,spid23s,Unknown,Error: 8565<c/> Severity: 16<c/> State: 1.
06/23/2015 22:22:50,spid23s,Unknown,Microsoft Distributed Transaction Coordinator (MS DTC) has stopped this transaction.
06/23/2015 22:22:50,spid23s,Unknown,Error: 8522<c/> Severity: 16<c/> State: 1.

Appreciate your help.

mardi 23 juin 2015

SQL IF null Replace with other column data

Hi I'm really new at sql,

i want to replace a null column to other column data in the same table.

Declare @ref As mgr.gl_jlhdr.ref_no
Declare @P_no As mgr.gl_jlhdr.jlno
IF ref = Null
Then ref = P_no
end if

pls help

error The type name 'mgr.gl_jlhdr.ref_no' contains more than the maximum number of prefixes. The maximum is 1.

lundi 22 juin 2015

SQL join to add missing rows

I am new to SQL and need some help. In a scenario I want to join on Teachers Table where I have Data of subject a teacher taught. I want to add some missing rows through join so that I can show the rows where a class is being taught in a year but missing its teachers details. Either in any term for all subjects.

Note there could be multiple no. Of terms in a year

Mapping Table Of teachers and Class they thought

Teacher Class
Aman    9th
Ankit   9th
Abhinav 10th
Bharat  10th

Mapping Table Of teachers and term in which they thought

Teacher Term
Aman    1stTerm
Ankit   2nd Term
Abhinav 2nd Term
Bharat  1stTerm

Data Table

Subject YEAR    Teacher Marks
Maths   2014    Aman    80
Maths   2014    Ankit   85
Maths   2015    Abhinav 69
Science 2014    Abhinav 30
Science 2015    Aman    20

Output Table

Subject Class   Teacher Class   Term        Marks
Maths   2014    Aman    9th     1stTerm     80
Maths   2014    Ankit   9th     2nd Term    85
Maths   2015    Abhinav 10th    2nd Term    69
Maths   2015    Bharat  10th    1stTerm     0
Science 2014    Abhinav 10th    2nd Term    30
Science 2014    Bharat  10th    1stTerm     0
Science 2015    Aman    9th     1stTerm     20
Science 2015    Ankit   9th     2nd Term    0

dimanche 21 juin 2015

How do I get Sum of two Colunms with Same Foreign Key

I have three tables: Carrier(C), DropShipper(D) and ShoppingCart(S) with the following schema

Table C

c.id(Pk,int,not null)
c.dropshipperid(Fk,int,not null)
c.Prodid(int, not null
c.cost(money null)

Table D

D.Dropshipperid(Pk,int,not null)
D.Dropshipper(nvarchar(50))
D.Remarks(nvarchar(50))

Table S

s.cartid(PK, char(36))
s.prodid(pk,fk,int not null)
s.qty(int not null)

Here are sample data:

c.id    c.dropshipperid  c.prodid    c.cost
--------------------------------------------
1            1             11          100
2            2             11          200
3           3             11          80
4            4             11           70
5            1             6          212
6            2             6          312
7           3             6          412
8           4             6          512


D.dropshipperid   D.dropshipper        D.Remarks
-------------------------------------------------
1                   Airmail               10-25days
2                    DHL                  23-5 days
3                     Fedex                6- 10days
4                       UPS                 4- 5days

S.cartid           s.prodid              s.qty
------------------------------------------------
   xxxx                 11                  2
    xxxx                 6                   2

And here is my sql

SELECT     D.DropShipper, C.Cost, D.Remarks,( S.Quantity * C.Cost)    AS  SubCost, S.CartID, C.DropShipperID, 
S.ProductID, C.ProductID AS cProductid,  S.Quantity
FROM C INNER JOIN D 
ON C.DropShipperID = D.DropShipperID 
INNER JOIN S 
 ON S.ProductID = S.ProductID
 WHERE (C.DropShipperID IN (1, 2, 3, 4, 5)) AND
(S.CartID = @cartid)

This is a sample result of my qry:

Dropshipper     cost     Remarkd     Subcost     Cartid    Dropshipperid
------------------------------------------------------------------------
   Airmail       100      Text         200        xxxx            1
   DHL           200                   400         xxxx           2   
   Fedex          80                   160         xxxx            3
   UPS            70                   140        xxxx            4
  Airmail         212                 414            xxxx          1
   DHL           312                  614          xxxx            2
   Fedex         412                  814         xxxx            3
   UPS           512                  1024        xxxx             4

Here is what I need:

I don Not what the DropShipperID duplicated, ie I need just one set. Then SubCost should be the sum of subcost for each dropshipperID. some thing like this

DropShipperID   DropShipper    SubCost    etc
------------------------------------------------
1                Airmail          614
2                DHL               1014
3                Fedex              974
4                UPS                 1164  

SQL SERVER LEFT JOIN on multiple columns with unwanted duplicates

I have been running in circles with a query that is driving me nuts.

The background:
I have two tables, and unfortunately, both have duplicate records. (Dealing with activity logs if that puts it into perspective). Each table comes from a different system and I am trying to join the data together to get a sudo full picture (I realize that I won't get a perfect view because there is no "event key" shared between the two systems; I am attempting to match on a composite of meta data).

Here is what I am working with:

    Table1 t1
    ------------
    JobID      CustID      Name      ActionDate      IsDuplicate
    12345      11111      Ryan      1/1/2015 01:20:20      False
    12345      11112      Bob      1/1/2015 02:10:20      False
    12345      11111      Ryan      1/1/2015 04:15:35      True
    12346      11113      Jim      1/1/2015 05:10:40      False
    12346      11114      Jeb      1/1/2015 06:10:40      False
    12346      11111      Ryan      1/1/2015 07:10:30      False

    Table2 t2
    ------------
    ResponseID      CustID      ActionDate      Browser
    11123      10110      12/1/2014 23:32:15      IE
    12345      11111      1/1/2015 03:20:20      IE
    12345      11112      1/1/2015 05:10:20      Firefox
    12345      11111      1/1/2015 06:15:35      Firefox
    12346      11113      1/1/2015 07:10:40      Chrome
    12346      11114      1/1/2015 08:10:40      Chrome
    12346      11111      1/1/2015 10:10:30      Safari
    12213      11123      2/1/2015 01:10:30      Chrome

Please note a few things:
- JobID and ResponseID are the same thing
- JobID and ResponseID are indicators of an event on the site (people are responding to an event)
- Action date does not match (system 2 has about an inconsistent 2 hour delay on it but never more that 3 hours delay)
- Note Table2 doesnt have a duplicate flag
- table 1 (~2,000 records) is significantly smaller than table 2 (~16,000 records)
- Note Cust 11111 is bopping around on browsers, taking the same action twice on job 12345 at different times and only taking action once on job 12346

What I am looking for:

    Result (ideal)
    ------------
    t1.JobID      t1.CustID      t1.Name      t1.ActionDate      t2.Browser
    12345      11111      Ryan      1/1/2015 01:20:20      IE
    12345      11112      Bob      1/1/2015 02:10:20      Firefox
    12345      11111      Ryan      1/1/2015 04:15:35      Firefox
    12346      11113      Jim      1/1/2015 05:10:40      Chrome
    12346      11114      Jeb      1/1/2015 06:10:40      Chrome
    12346      11111      Ryan      1/1/2015 07:10:30      Safari

Note that I JUST want matches for records in Table1. I am getting tons of duplicates because of the join...Which is frustrating.

Here is what I have so far (which I can humbly can say; isn't really close):

    SELECT
    t1.JobID,
    t1.CustID,
    t1.Name,
    t1.ActionDate,
    t2.Browser
    FROM
    Table1 t1
    LEFT OUTER JOIN
    Table2 t2
    ON
    t1.JobID=t2.ResponseID AND 
    t1.CustID=t2.CustID AND
    DATEPART(dd,t1.ActionDate)=DATEPART(dd,t2.ActionDate)

Any help with this would be greatly appreciated.

samedi 20 juin 2015

sql query to join and concat values

sql server: 2012

These are 3 tables.

First table is the user's (consultants) table The second one is the prices table, each user from the first column has a price The last table define in what area (city) the consultants offer services

Consultants      Prices           Area
uid | Name       uid | Price      uid | City
----|-----      -----|-------     ----|------
1   | Dave        1  |  5           1 | NY
2   | Adrian      2  |  7           1 | LA
3   | John        4  |  5           4 | NY
4   | Lee                           4 | NO
                                    4 | LA 
                                    4 | SF

I need to select from all the table something like this:

uid  |  Price   | City
-----|----------|-------
 1   |    5     | NY, LA
-----|----------|-------
 2   |    7     | 
-----|----------|-------
 4   |    5     | NY, NO, LA, SF
-----|----------|-------

How do I do this select? Any idea?

vendredi 19 juin 2015

Can someone help me with Formatted HTML Table with TSQL

I created a SQL server job with query ( as shown below) that dynamical retrieve set of data, generates html table and email it to a recipient. The Job work fine as long as the query returns a record set which renders the html tableas shown in the attached image.On the contrary, when the query returns no record set, the recipient gets a blank email instead of a table with default values or null values. Does anyone know how to tweak this code to render html table with default value of zeros whenever the query returns no record set?

    use dev;
               declare @tableHTML  nvarchar(max);

         set @tableHTML =N'<H3><font color="Red">' + 
         'The Exams Attempt for the   month of' + ' ' 
`             ` + DATENAME(MONTH, (DATEADD(MONTH,-1,DATEADD(month, DATEDIFF(month, 0, ![alt text][1]getdate()), 0))) ) + '</H3>' +

   '<td>' + N'<table border="1">' +    
                            '<caption>' + '3rd Attempt' + '</caption>'+
                             N'<tr><th>app_lvl</th>' +
                             N'<th>EligAtt</th>' +
                             N'<th>Category</th>' +
                             N'<th>Result</th>' +
                             N'<th>Count</th>' +
                             CAST ( ( SELECT td = sc_pracrslts.reg_lvl, '',td = sc_pracrslts.elig_attmpt_no, '',td = sc_pracrslts.category, '',td = sc_pracrslts.pass_ind, '',td = count(*), ''

                         FROM ARS_copy..sc_pracrslts
                         WHERE exam_dt >= '4/1/2015' and exam_dt < '5/1/2015'  AND
                            sc_pracrslts.elig_attmpt_no = 3
                            and sc_pracrslts.category = '1' 
                         GROUP BY sc_pracrslts.reg_lvl,   
                                  sc_pracrslts.category,   
                                  sc_pracrslts.elig_attmpt_no,   
                                  sc_pracrslts.pass_ind  
                         ORDER BY sc_pracrslts.reg_lvl,   
                                  sc_pracrslts.category,   
                                  sc_pracrslts.elig_attmpt_no,   
                                  sc_pracrslts.pass_ind
                           FOR XML PATH('tr'), TYPE 
                 ) AS NVARCHAR(MAX) ) 

                 + N'</table>' +
          '</td>' +


         '</tr>' +  '</table>';



                    EXEC msdb.dbo.sp_send_dbmail
                  @recipients=N'aboamah@ABC.org',
                  @subject = 'Exams Attempt Dashboard ',
                  @body = @tableHTML,
                  @body_format = 'HTML' ,
                  @profile_name='Augie Bomah'


I tried the ISNULL on each column and put some value. Like:

           SELECT  td = ISNULL(sc_pracrslts.reg_lvl, 'NULL') ,
             '' ,
  ![enter image description here][1]                 td = ISNULL(sc_pracrslts.elig_attmpt_no, 'NULL') ,
                    '' ,
                   td = ISNULL(sc_pracrslts.category, 'NULL') ,
                   '' ,
                  td = ISNULL(sc_pracrslts.pass_ind, 'NULL') ,
                  '' ,
                   td = COUNT(*) ,

but it didn't work !!

SQL - replace returned data with other data

I am retrieving data using the SQL syntax below:

SELECT TOP 5 EventId, EventTime, DeviceName, Comment, Tenant, TenantName, Individual, 
                InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName, InetDb.dbo.IndivImages.UserImage
                FROM taclogdata.dbo.Event
                LEFT JOIN InetDb.dbo.Tenants
                    ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
                LEFT JOIN InetDb.dbo.Individuals
                    ON taclogdata.dbo.Event.Individual = InetDb.dbo.Individuals.IndivId 
                    AND taclogdata.dbo.Event.Tenant = InetDb.dbo.Individuals.TenantNdx
                LEFT JOIN InetDb.dbo.IndivImages
                    ON InetDb.dbo.Individuals.IndivId = InetDb.dbo.IndivImages.IndivNdx
                    AND InetDb.dbo.Individuals.TenantNdx = InetDb.dbo.IndivImages.TenantNdx
                WHERE (taclogdata.dbo.Event.EventTime  > DATEADD(hh, -3, GETDATE())AND taclogdata.dbo.Event.EventTime < GETDATE())
                    AND (taclogdata.dbo.Event.Comment='Reader entry' OR taclogdata.dbo.Event.Comment='Reader exit')
                    AND (taclogdata.dbo.Event.DeviceName = 'L9 1/4/1' 
                        OR taclogdata.dbo.Event.DeviceName='L1 2/1/1-2 MainD'
                        OR taclogdata.dbo.Event.DeviceName='L1 2/1/3-4 MainD'
                        OR taclogdata.dbo.Event.DeviceName='L1 2/6/1-2 Stair'
                        OR taclogdata.dbo.Event.DeviceName='L1 2/2/1-2 FDT1')
                ORDER BY taclogdata.dbo.Event.EventTime DESC

This code works fine, however I'm trying to simplify the results.
I'm trying to simplify what the query returns, by replacing the DeviceName value from e.g. L1 2/1/3-4 MainD to Main Door when the results are shown (not replace the actual data in the database)

How may I achieve this please ?
Thanks in advance,
J

Import .bak into sql management studio 2008

I have a custom program that uses a database. I have little knowledge of servers but the way it works is by using a "local" server in the same computer as the one where the program is installed. I am trying to install the program in a new computer but I don't know how to set up the database.

What I have is a .bak file of the database and a list of the programs that are needed to have the "server" running:

-SQL Server Management Studio 2008

-SQL Server Configuration Manager

-SQL Server Surface Area Configuration 2005

Excuse me for my ignorance, but I believe this should be a very simple thing to do, however I am overwhelmed by all the information that there is so I would like to be pointed in the right direction.

Thanks.

vb.net auto update datagridview when database change

I have an application where multiple users can connect to a database and datagridview need to be updated automatically when there has been a change in the database. Possible without timers?

jeudi 18 juin 2015

Get Active Directory Name From SQL User ID

I have a SQL table that contains active directory IDs, but no names. So, the core of the issue is that I need to find the associated names. I have tried to just use SQL to query the active directory, but I have run into issues with that, so my next attempt is to use C#.NET and display those IDs and their associated active directory "givenname" on the page.

I am currently trying to do this using a Gridview, but I am not particular about how it is displayed.

The effort below represents my attempt to dynamically create a gridview column next to the ID column and populate it with the associated name of the user.

protected void Page_Load(object sender, EventArgs e)
    {

        //Tabs
        if (!IsPostBack)
        {

            string connection = "LDAP://....";
            using (DirectoryEntry DE = new DirectoryEntry(connection))
            {
                DataTable dt = new DataTable();
                dt = connStringClass.ExecuteDataTable("spIDsSelect", connStringClass.DB);

                DirectorySearcher dssearch = new DirectorySearcher(connection);
                dssearch.Filter = "(userID=" + gvLookup.Columns + ")";

                SearchResult sresult = dssearch.FindOne();
                if (sresult != null)
                {
                    DirectoryEntry de = sresult.GetDirectoryEntry();

                    foreach (DataRow row in gvLookup.Rows)
                    {
                        DataColumn col = new DataColumn();
                        BoundField field = new BoundField();
                        field.HeaderText = col.ColumnName;
                        field.DataField = de.Properties["givenname"][0].ToString();
                        gvLookup.Columns.Add(field);
                    }
                }
                else
                {
                    Response.Write("No results.");
                }
            }

        }
    }
}


<asp:TemplateField HeaderText="ID" SortExpression="recID" Visible="false">                                
    <ItemTemplate><asp:Label ID="lbRecID" runat="server" Text='<%# Bind("recID") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID" 
    HeaderStyle-HorizontalAlign="Left" SortExpression="ID">
    <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:BoundField>

How do I return records based on which records only exist during a certain time period?

I've got a table of invoices and customer codes. I'd like to pull only the customers that have not done any business with us since 2009.

My regular select statement is simple

SELECT INVOICE.CUSTOMER_CODE FROM INVOICES

WHERE INVOICES.ORDER_DATE <= '01-01-2010'

But, this statement also pulls customer codes of customers who have done business before and after 2010. I want only those customers that have not done business before 2010. It seems so simple, but I can't grasp how to do this and my google searches only bring up how to do a range of dates.

mercredi 17 juin 2015

Is there a way to re-write this SQL query using a WITH clause or any other CTE that might be even better?

As you can see below, there is a SQL query inside of a SQL query inside of another SQL query. Is there any way I can give these queries an alias and call that alias in the proceeding query instead of re-writing it completely? I was trying to do it using a WITH clause but ended up with countless errors that I couldn't seem to get around. Any possible way to reduce this without having to re-write a query is pretty much what I'm looking for. I'm using Microsoft SQL Server 2005 by the way.

select 
MNumber, 
CDate,
(select MAX(CDate) 
from tbl_MeterCalib MC2 
WHERE MC2.MNumber= MC1.MNumber
AND CDate< MC1.CDate) as PrevCalDate,

datediff(d,(select MAX(CDate) 
from tbl_MeterCalib MC2 
WHERE MC2.MNumber= MC1.MNumber
AND CDate< MC1.CDate),CDate)/2 as AdjPeriod,

dateadd(d, -datediff(d,(select MAX(CDate) 
from tbl_MeterCalib MC2 
WHERE MC2.MNumber= MC1.MNumber
AND CDate< MC1.CDate),CDate)/2,CDate) as DaysBackTo

from tbl_MeterCalib MC1

Any help would be greatly appreciated! Thank you!

MSSQL UNION ALL on 2 Table Selects With WHEN Cases

In short, I tried asking for help on an SQL forum...they are very slow to let the post go live and after waiting around 26 hours now decided to try to ask for help at Stack.

I'm running MS SQL 2005. I have 2 tables with the same columns but holding very different data.

SELECT * FROM Table1 WHERE ItemID IN ('4','2','1') ORDER BY CASE  WHEN ItemID = 4 then 1 WHEN ItemID = 2 then 2 WHEN ItemID = 1 then 3 END 
UNION ALL 
SELECT * FROM Table2 WHERE ItemID IN ('3','1','5','2') ORDER BY CASE  WHEN ItemID = 3 then 4 WHEN ItemID = 1 then 5 WHEN ItemID = 5 then 6 WHEN ItemID = 2 then 7 END

I need to keep the order of the ItemID in the order that they are selected which is why I used CASE. This all works fine on each table but I can't find a way to combine them into 1 table of results with the results of each table ordered.

ie.

4 (Table1)
2 (Table1)
1 (Table1)
3 (Table2)
1 (Table2)
5 (Table2)
2 (Table2)

Extremely grateful for any and all help.

mardi 16 juin 2015

SQL Server convert varchar column to computed column without losing existing column data

Is it possible to convert a normal column to a computed column (persisted) without losing the existing data? The older data in the column doesn't quite follow the pattern I want to implement, but would work fine with the newer data.

The only way I could think of doing it is rename the column, create a new column, write a function that would first populate from old column, if null use formula.

I've tried setting a default binding, but I need the value of another column for my function and that doesn't seem to work.

I'm also trying to avoid a trigger because I'm using a generic "insert output inserted" statement and triggers cause a DML statement error.

Hope that makes sense. Thank you.

lundi 15 juin 2015

Optimization issue with user defined function

I have a problem understanding why SQL server decides to call user defined function for every value in the table even though only one row should be fetched. The actual SQL is a lot more complex, but I was able to reduce the problem down to this:

select  
    S.GROUPCODE,
    H.ORDERCATEGORY
from    
    ORDERLINE L
    join ORDERHDR H on H.ORDERID = L.ORDERID
    join PRODUCT P  on P.PRODUCT = L.PRODUCT    
    cross apply dbo.GetGroupCode (P.FACTORY) S
where   
    L.ORDERNUMBER = 'XXX/YYY-123456' and
    L.RMPHASE = '0' and
    L.ORDERLINE = '01'

For this query, SQL Server decides to call GetGroupCode function for every single value that exists in PRODUCT Table, even though the estimate and actual number of rows returned from ORDERLINE is 1 (it's the primary key):

Query Plan

Same plan in plan explorer showing the row counts:

Plan explorer Tables:

ORDERLINE: 1.5M rows, primary key: ORDERNUMBER + ORDERLINE + RMPHASE (clustered)
ORDERHDR:  900k rows, primary key: ORDERID (clustered)
PRODUCT:   6655 rows, primary key: PRODUCT (clustered)

The index being used for the scan is:

create unique nonclustered index PRODUCT_FACTORY on PRODUCT (PRODUCT, FACTORY)

The function is actually slightly more complex, but the same thing happens with a dummy multi-statement function like this:

create function GetGroupCode (@FACTORY varchar(4))
returns @t table(
    TYPE        varchar(8),
    GROUPCODE   varchar(30)
)
as begin
    insert into @t (TYPE, GROUPCODE) values ('XX', 'YY')
    return
end

I was able to "fix" the performance by forcing SQL server to fetch the top 1 product, although 1 is max that can ever be found:

select  
    S.GROUPCODE,
    H.ORDERCAT
from    
    MILLORDERLINE M
    join ORDERHDR H
        on H.ORDERID = M.ORDERID
    cross apply (select top 1 P.MILLBU from PRODUCT P where P.PRODUCT = M.PRODUCT) P
    cross apply dbo.GetGroupCode (P.MILLBU) S
where   
    M.MILLORDNO = 'OFDE-500002' and
    M.MACHCHAINNO = '0' and
    M.ORDERLINENO = '01'

Then the plan shape also changes to be something I expected it to be originally:

Query Plan with top

I also though that the index PRODUCT_FACTORY being smaller than the clustered index PRODUCT_PK would have an affect, but even with forcing the query to use PRODUCT_PK, the plan is still the same as original, with 6655 calls to the function.

If I leave out ORDERHDR completely, then the plan starts with nested loop between ORDERLINE and PRODUCT first, and the function is called only once.

I would like to understand what could be the reason for this since all the operations are done using primary keys and how to fix it if it happens in a more complex query that can't be solved this easily.

Get Parent and grand parents of a particular child

i have table like below

tablename :ExampleTable

ChildID       ChildCommonID   ParentID


1               2                0

2               3                0

3               4                1

4               5                3

5               6                4

The Problem is :

i have a child id example :ChildID= 5

so i need to check wheather it has a parent or not if it contain a parent then check the corresponsing parentid, in this case the parentID is 4 so need to check the child 4 has any parent ,in this case parentID of child 4 is 3, so gain check child 3 has any parent in this case child 3 has parent 1, so check child 1 has any parents here child 1 is the top grand parent and it has no parent so stop the process and return all childids up to 1

Here the expected output is

ChildID

5
4
3
1

i had tried something like below but it does not give correct output

with getallparent as (
   select * 
   from ExampleTable 
   where ChildID  = 5 
  union all 
  select *
   from ExampleTable c 
     Left join getallparent p on p.ChildID = c.ParentID 
) 
select *
from getallparent;

If you need the sample data you can use the below query

create table ExampleTable(ChildID int,ChildCommonID int ,ParentID int )
insert into ExampleTable values(1,2,0)
insert into ExampleTable values(2,3,0)
insert into ExampleTable values(3,4,1)
insert into ExampleTable values(4,5,3)
insert into ExampleTable values(5,6,4)

Any help will be appreciated

dimanche 14 juin 2015

Selecting from a column with Ampersand(&)

The data type of the column is nvarchar. I can insert to the column properly using parameters. I see the ampersand character in the column when I view the table in sql server management studio.

My problem is when i'm selecting from the column in my application the ampersand character disappears.

Once I select the column I assign the value to a label like, label1.Text = reader("column")

The column in my table has a value of "Foo&Bar" but in my application it just shows as "FooBar".

vendredi 12 juin 2015

How to compare two date in SQL Server 2005?

How can I convert date value into format of dd-MM-yyyy in SQL? I have stored date into database in varchar(10) format. Now want to compare date from 1-05-2015 to 31-06-2015.

Query is :

select date
from dates
where date >='1-05-2015' and date <='10-06-2015'

it returns only (same result in use of between)

  1. 1-06-2015
  2. 10-06-2015
  3. 1-07-2015

I cannot use Format Method because 2005 not support. I tried Convert method but not helpful.

Different SELECT's for an INSERT INTO

I'm trying to have an IF block after an INSERT INTO statement and depending on some conditions, execute a different SELECT that will feed the INSERT INTO.

Here's a (failing) example of what I'm trying to do:

INSERT INTO #TempTable (COL1, COL2, COL3)
    IF @VAR = 'YES'
        BEGIN
            SELECT * FROM TABLE
        END
    ELSE
        BEGIN
            SELECT * FROM TABLE WHERE REGDATE <= '2015-06-12'
        END

But I always end up with this when trying to save the stored proc.

Incorrect syntax near the keyword 'IF'

Any other approach ? I thought of building a string and using sp_executesql but I think my initial approach would be less prone to error.

Thanks.

SSRS Report is Blank

I am trying to change an existing report to get the data from the new stored procedure. The stored procedure is fine and it shows the data correctly.

enter image description here

But when I got to the "Preview" Tab and run the report its blank. I event check with the sql profiler an it does not call the stored procedure at all. The dataSet is correct and I am not sure what am I missing!! Here is the image after I test the report in the preview:

enter image description here

SQL Insert Date Mystery on 2012 from 2005

I have migrated a 2005 db to 2012

There is a stored procedure that run to insert todays date into a table

IF NOT EXISTS(SELECT * FROM tblTime WHERE [Day] = DATEPART(day,GETDATE())
                                    AND [Month] = DATEPART(month,GETDATE())
                                    AND [Year]= DATEPART(year,GETDATE()) )
BEGIN
    INSERT INTO tblTime (Period,[Day],[Month],[Year],MonthPrefix)
        VALUES (CONVERT(VARCHAR(10), GETDATE(), 105),
                DATEPART(day,GETDATE()),
                DATEPART(month,GETDATE()),
                DATEPART(year,GETDATE()),
                CASE DATEPART(month,GETDATE()) 
                    WHEN 1 THEN 'JAN'
                    WHEN 2 THEN 'FEB'
                    WHEN 3 THEN 'MAR'
                    WHEN 4 THEN 'APR'
                    WHEN 5 THEN 'MAY'
                    WHEN 6 THEN 'JUN'
                    WHEN 7 THEN 'JUL'
                    WHEN 8 THEN 'AUG'
                    WHEN 9 THEN 'SEP'
                    WHEN 10 THEN 'OCT'
                    WHEN 11 THEN 'NOV'
                    WHEN 12 THEN 'DEC'
                    END
                )
END

When this is run on the new 2012 SQL box the date gets put in as

2015-12-06 00:00:00

But the same SP on the old 2005 would read

2015-06-12 00:00:00

I have checked that the 2 servers have the same language settings etc.

But is there something I have missed.

Many thanks for reading.

jeudi 11 juin 2015

SQL SERVER 2000 QUERY CONVERSION

I have a query written in sql server 2000 and I want to re-write that to use in sql server 2005 and newer versions. here is the query:

IF @AgrpID > 0 SELECT @Sql = @Sql + ' AND C.AGRP_ID = ' + CONVERT(VarChar(10), @AgrpID)

P.S: COM.DBO.CNTL_ContactCenterLeads C I dont undrestant what is the

SELECT @Sql = @Sql + ' AND C.AGRP_ID = ' + CONVERT(VarChar(10), @AgrpID)

does, and if I have a #temp table replace with @sql, how can I re-write this query with the same logic.

PHP error connecting to MS SQL 2005 using Code Igniter

Good day!

I'm encounter an error every time I'm connecting to my MS SQL 2005 server using Code Igniter framework, I'm using PHP 5.6.8 version.

"Fatal error: Call to undefined function sqlsrv_connect() in C:\xampp\htdocs\my_website\system\database\drivers\sqlsrv\sqlsrv_driver.php on line 76"

I already add dll files php_pdo_sqlsrv_56_ts.dll and php_sqlsrv_56_ts.dll to ext folder and on my php.ini, and install Microsoft SQL Native Client 2012, this is my code in the sqlsrv_driver.php line 76 -> return sqlsrv_connect($this->hostname, $connection);

I already setup and install all needed files but still I encounter this error, So I create a sample php file to test if I will connect to datatbase w/out using a framework and its successfully connected in MS SQL server. but not I if used code igniter.

Did I missed some code, configuration or software to install? thanks for usual support!

This is my database.php

$db['default']['hostname'] = 'MY-PC\MSSQL2005';
$db['default']['username'] = 'sa';
$db['default']['password'] = 'password';
$db['default']['database'] = 'MYDB';
$db['default']['dbdriver'] = 'sqlsrv';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

UPDATE after INSERT for potentially multiple rows - not working

I have the following trigger which doesn't work and I'm not sure why. The trigger should fire after an insert into the REFERRALS table and I've allowed for the possibility of multiple rows being inserted. The value of ORIGINAL_PATIENT_ID in the REFERRALS table should be set to the value of PATIENT_ID in Inserted, but it just doesn't work, i.e. the value of ORIGINAL_PATIENT_ID remains NULL.

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[updateOSC]'))
DROP TRIGGER [dbo].[updateOSC]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[updateOSC]
ON [dbo].[REFERRALS]
AFTER INSERT

AS

BEGIN

SET NOCOUNT ON
IF (SELECT ORIGINAL_PATIENT_ID FROM Inserted) IS NULL
UPDATE [dbo].[REFERRALS] 
SET  ORIGINAL_PATIENT_ID = i.PATIENT_ID 
FROM Inserted i
WHERE dbo.REFERRALS.PATIENT_ID = i.PATIENT_ID
END
GO

mardi 9 juin 2015

Error connecting to SQL Server 2005 in Java: Error reading prelogin response

I'm trying to connect with a SQL Server 2005 using Java but I'm getting an Exception that I don't know how to solve. I treid to googled it but I can't find exactly the same problem that is happening to me.

This is the code I'm using:

String url = "jdbc:sqlserver://IP:80"+";databaseName=intranetBD";
try {
        Connection con = DriverManager.getConnection(url, "sa", "pass");
        System.out.println("Conectado correctamente!");
        con.close();
} catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}

And the exception that I'm getting:

Advertencia: ConnectionID:1 ClientConnectionId: ced601b1-e1be-4057-924e-cc701abcc52b Prelogin error: host [IP] port 80 Error reading prelogin response: Connection reset ClientConnectionId:ced601b1-e1be-4057-924e-cc701abcc52b
com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset ClientConnectionId:ced601b1-e1be-4057-924e-cc701abcc52b
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
at com.microsoft.sqlserver.jdbc.TDSChannel.read(IOBuffer.java:1789)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.Prelogin(SQLServerConnection.java:1424)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1319)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at org.sts.recursosComunes.Pruebas.PruebasNeus.pruebaConexionSQLServer(Pruebas.java:85)
at org.sts.recursosComunes.Pruebas.PruebasNeus.main(Pruebas.java:65)

Any idea why is it happening and how to solve it?

Thank you!

sqlsrv_query doesn't return false on faulty T-SQL query

I'm using sqlsrv to connect to a MSSQL database. A feature in a secured (and only available to a few people) intranet application provides a box to write T-SQL code and execute them to the database. At this moment I'm working on a feature to test the given query.

First the query is validated for proper intent (e.g. if INSERT , UPDATE , DELETE , SHOW , CREATE , etc. is found the query will not execute). If that succeeds I'm trying to test the query. When I provide a faulty SQL query I still get a resource as result from sqlsrv_query instead of false (as described as expected behavior here: http://ift.tt/1mZuZLz). Note: the query truly is false (funny sentence..), in SQL Server Management Studio the query fails as expected.

Below my function testQuery(string $query):

public static function testQuery($query) {
    sqlsrv_configure('WarningsReturnAsErrors', 1);
    $statement = sqlsrv_query(self::$instance, $query);

    if($statement === false) {
        $errors = sqlsrv_errors(SQLSRV_ERR_ALL);

        if(!is_null($errors)) {
            return $errors;
        }

        return false;
    }

    return true;
}

Use of or abandoning the sqlsrv_configure() doesn't make a difference. The database I'm querying is a MSSQL 2005 database.

Suggestions?

lundi 8 juin 2015

use query results for another query sql

I know that there are many topics discussing nested queries, however I am getting errors on my nested query due to the functions I am using. I am using SQL Server 9.

I am looking to query the last 7 DATES with data (may not be the last 7 days).

My query to return the last 7 Dates with data works well.

   -- Set the return record count to the last 7 days
    SET ROWCOUNT 7
--Get the Distinct Dates
  SELECT DISTINCT(CONVERT(VARCHAR, CONVERT(DATETIME,[TestDate]),23)) AS DT

  FROM [SERVER].[dbo].[TABLE]  
  --Get the last 60 days
  WHERE   [TestDate]  BETWEEN (Getdate() - 60) AND Getdate() 
  --Start at the current date and go backwards.
 ORDER BY DT DESC
 --  reset the return record count to prevent issues with further queries.
 SET ROWCOUNT 0

This provides the following result:

DT
2015-05-29
2015-05-27
2015-05-26
2015-05-22
2015-05-19
2015-05-18
2015-05-15

Now, I want to use those 7 entries to pull the data for those dates.

Usually I would do a

SELECT * WHERE [TestDate] >= '2015-05-29' AND [TestDate] <= '2015-05-30' 

for example (cumbersome I know).

A) I get errors with the SET function in a nested query.

B) How to make the proper WHERE statement. One option is to use the first and last result (2015-05-29 and 2015-05-15) from the query

(WHERE [TestDate] >= 'FIRST_RESULT' AND [TestDate] <= 'LAST_RESULT')

vendredi 5 juin 2015

Get Table name from another query result

I have a table as like below:

Table AuditLog(
Reference varchar(10) [primary key],
TableName varchar(10),
ModifiedColumn varchar(10),
ChangeData varchar(max),
TableReference varchar(10)
)

I am trying to achieve following query:

select *,
    (select accountNumber from [AuditLog.TableName] where Reference = AuditLog.TableReference ) 
    from AuditLog

AuditLog table column 'TableName' contain table name of that database. I need to load accountnumber from that table base on TableReference.

What's the right way to have table name populated dynamically?

SSIS Execute SQL Task Stored Procedure returning empty result sets

I have a simple stored procedure that returns 1 row with 3 columns. I am trying to create an SSIS package that reuses the values in these columns later. If I run a simple select query everything is happy but when I run the stored procedure I get the following error:

[Execute SQL Task] Error: Executing the query "rs_UpdateMemberExtract" failed with the following error: "Unable to populate result columns for single row result type. The query returned an empty result set.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I've set up an ado.net connection and the proc runs correctly in SSMS, I have the task set up like follows:

ConnectionType: ADO.NET Connection: ServerName.connectionName SQLSourceType: Direct Input SQLstatment: Name of Proc (rs_UpdateMemberExtract) IsQueryStoredProcedure: True

I have each parameter mapped to a variable and the direction set to Output

I have the name of each column that should be returned in the result set and mapped to the associated variable.

The task works if I set the ResultSet to 'None',

Any ideas What I've missed?

Thanks

Second maximum value by using dense rank function

i have table like

name marks raja 88 ravi 88 karthik 99 praveen 99 vijay 70

in that table i assumee the rank of the table is '

name   marks rank 
raja    88    1
ravi    88    2
karthik  99   3
praveen  99   4
vijay    70   5

iget that by using dense rank function

select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D order by marks desc

but what i need is from that bove thabe i need to get second lowest rank i mena the output i want is "praveen 99 4"

i tried to get thesecond lowest rank but i cant get the all the columns ,i tried thse query

select max(a.ranks) as b from (
select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D ) as a where a.ranks not in
(

select max(a.ranks) as b from (
select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D ) as a )

jeudi 4 juin 2015

Query to get report name, reports first and last run time and date, how often it was run and method of delivery (email or locations)

I am new to sql server.

I have been trying to write a query to get report name, reports first and last run time and date, scheduled by ,how often it was run and method of delivery (email or locations) for SQL Server 2005.

Please help me with this.

How to check what type of lock an UPDATE statement uses?

How can I determine if an update statement puts a table lock, page lock, or row lock on a table?

dateadd() is not working as desired to find the date of 7 days from now sql-server

I am trying to find the date of 7 days from a specific date. To do this I tried

Select @Fromdate = DATEADD(day,-7, max(last_update)), @todate= max(last_update)
FROM vwABC

But it is not working and when I tried the following every thing works fine.

SELECT @Fromdate = '20150601', @ToDate = MAX(last_update)
FROM vwABC

I cant understand, whats the problem. Please help.

SQL Server - cumulative sum on overlapping data - getting date that sum reaches a given value

In our company, our clients perform various activities that we log in different tables - Interview attendance, Course Attendance, and other general activities. I have a database view that unions data from all of these tables giving us the ActivityView that looks like this. As you can see some activities overlap - for example while attending an interview, a client may have been performing a CV update activity.

+----------------------+---------------+---------------------+-------------------+
| activity_client_id   | activity_type | activity_start_date | activity_end_date |
+----------------------+---------------+---------------------+-------------------+
|                  112 | Interview     | 2015-06-01 09:00    | 2015-06-01 11:00  |
|                  112 | CV updating   | 2015-06-01 09:30    | 2015-06-01 11:30  |
|                  112 | Course        | 2015-06-02 09:00    | 2015-06-02 16:00  |
|                  112 | Interview     | 2015-06-03 09:00    | 2015-06-03 10:00  |
+----------------------+---------------+---------------------+-------------------+

Each client has a "Sign Up Date", recorded on the client table, which is when they joined our programme. Here it is for our sample client:

+-----------+---------------------+
| client_id | client_sign_up_date |
+-----------+---------------------+
|       112 | 2015-05-20          |
+-----------+---------------------+

I need to create a report that will show the following columns:

+-----------+---------------------+--------------------------------------------+
| client_id | client_sign_up_date | date_client_completed_5_hours_of_activity |
+-----------+---------------------+--------------------------------------------+

We need this report in order to see how effective our programme is. An important aim of the programme is that we get every client to complete at least 5 hours of activity as quickly as possible. So this report will tell us how long from sign up does it take each client to achieve this figure.

What makes this even trickier is that when we calculate 5 hours of total activity, we must discount overlapping activities:

In the sample data above the client attended an interview between 09:00 and 11:00.
On the same day they also performed CV updating activity from 09:30 to 11:30. For our calculation, this would give them total activity for the day of 2.5 hours (150 minutes) - we would only count 30 minutes of the CV updating as the Interview overlaps it up to 11:00.

So the report for our sample client would give the following result:

+-----------+---------------------+--------------------------------------------+
| client_id | client_sign_up_date | date_client_completed_5_hours_of_activity |
+-----------+---------------------+--------------------------------------------+
|       112 | 2015-05-20          | 2015-06-02                                 |
+-----------+---------------------+--------------------------------------------+

So my question is how can I create the report using a select statement ? I can work out how to do this by writing a stored procedure that will loop through the view and write the result to a report table. But I would much prefer to avoid a stored procedure and have a select statement that will give me the report on the fly.

I am using SQL Server 2005.

mercredi 3 juin 2015

Not able to do automatic conversion of scripts from sql server 2008 to 2005

I have stored procedures created in sql server 2008 R2. Now, one of our clients is using Sql Server 2005, and scripts need to be converted to old version as there is syntax incompatibility like date is not supported in sql server 2005. Since the number of stored procedures is large, 364 in my case, doing it manually will take me days as I need to check for every supported/unsupported syntax.

What I tried :

I tried to generate scripts by setting option of Scripts for Sql version as 2005, but still scripts generated doesn't contain correct syntax as in case of replacing date with datetime.

Is there any other way, should Sql server not do it automatically!!

Selecting Min/Max from Comma Separated Values against each record

consider below table and its records

create table dbo.test
(
id  numeric(4),
vals    nvarchar(1000)
);

insert into dbo.test values (1,'1,2,3,4,5');
insert into dbo.test values (2,'6,7,8,9,0');
insert into dbo.test values (3,'11,54,76,23');

I am going to use below function to split CSVs, you can use any method to help in select syntax

CREATE FUNCTION [aml].[Split](@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (items varchar(8000))     
as     
begin     
declare @idx int     
declare @slice varchar(8000)     

select @idx = 1     
    if len(@String)<1 or @String is null  return     

while @idx!= 0     
begin     
    set @idx = charindex(@Delimiter,@String)     
    if @idx!=0     
        set @slice = left(@String,@idx - 1)     
    else     
        set @slice = @String     

    if(len(@slice)>0)
        insert into @temptable(Items) values(@slice)     

    set @String = right(@String,len(@String) - @idx)     
    if len(@String) = 0 break     
end 
return     
end

I want to select id and max and min values from vals against each record.

Access 2010 SQL query works fine by itself but not when linked to access db

Access 2010 inventory db of items(item, location, qty etc...). linked SQL server 2005 tables of orders. I've created an Access SQL query to retrieve a list of items for a particular order number. This runs fine by itself, but when I add links to my Access db, asking it for the location and qty, it only shows results for 1 item(last item)? I feel like I'm missing something simple. I somewhat know my way around access but not so much in SQL and basically new to any programming languages. Since I can't post photos yet I'll attempt to show examples of what is returned. SQL Order query-- Headers Order_no, Item_no Results 00123, 77000; 00123, 77013; 00123, 77006; 00123, 77010; etc... SQL order query with inventory--Headers Order_no, Item_no, Location, Qty Results 00123, 77006, bin3, 24; 00123, 77006, bin4, 32; 00123, 77006, bin7, 21; 00123, 77006, bin14, 10. Any ideas would be appreciated. Thanks

mardi 2 juin 2015

how to calculate ratio of data in two tables in sql

i have a table emp which has count of employees company wise and another table which has count of employees whose age is greater than 18 company wise. Now i want to display the percentage of employees who are greater than 18 companywise

lundi 1 juin 2015

SQL - Select first n occurrences of each value

Let's say I have a table like so, only with thousands of records.

| Foo | Bar  | 
| 1   | A_1  | 
| 1   | A_2  | 
| 2   | B_1  | 
| 3   | B_1  | 
| 3   | B_2  | 
| 3   | B_1  | 
| 4   | B_3  | 
...

When I execute the code below, I obviously get each and every record where Bar begins with B.

SELECT Foo
FROM tableName
WHERE Bar LIKE 'B%'

I know using GROUP BY will get me the first 1 record of each, but I need more than just that. Using SELECT TOP 100 will only net me the first 100 records, regardless of which "B" they are, and since there are far more than 100 B_1 values, that's all that I will get.

How can I only get the first n records for each unique B? For example, the first 100 occurrences of B_1, the first 100 of B_2, etc.

Dotnetnuke migration from SQL 2005 to SQL 2012

I'm trying to upgrade my DNN v6 from a SQL Server 2005 to a SQL Server 2012. My problem is, after modifying the web.config to match the new appSettings, my website automaticaly runs the install wizard. My IIS was running on a 2003 server and is now on a 2012 server.

Is it a necessary step to install a new instance of DNN?

Thanks for your help

Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF. Entity Framework 6. Only fails on one table

Please can anyone help with this issue I'm having. I've exhausted the current suggestions on here.

We are rewriting an application in MVC EF6 Codefirst using the existing database structure (SQL 2005).

The SQL Script for the table in question:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblStaff](
[staffID] [int] IDENTITY(1,1) NOT NULL,
[firstName] [nvarchar](50) NOT NULL,
[lastName] [nvarchar](50) NOT NULL,
[Alias] [nvarchar](50) NULL,
[addressID] [int] NULL,
[teamID] [int] NULL,
[managerID] [int] NULL,
[clientID] [int] NULL,
[jobTitle] [int] NULL,
[activeFlag] [bit] NULL,
[contractorID] [int] NULL,
[fullName] [nvarchar](101) NULL,
[securityTrainingDate] [datetime] NULL,
[CRBCheckDate] [datetime] NULL,
[CMSTrainingDate] [datetime] NULL,
 CONSTRAINT [PK_tblStaff_1] PRIMARY KEY CLUSTERED 
(
    [staffID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,     ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)     ON [PRIMARY]

GO

The Model code in the application:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CMS3.Model.DBTables
{

public class tblStaff
{
 //   [ColumnAttribute(IsPrimaryKey = true, IsDbGenerated = true)]

    [Key]
    public int staffID { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string Alias { get; set; }
    public int? addressID { get; set; }
    public int? managerID { get; set; }
    public int? clientID { get; set; }
    public int? jobTitle { get; set; }
    public bool? activeFlag { get; set; }
    public int? contractorID { get; set; }
    public string fullName { get; set; }
    public DateTime? securityTrainingDate { get; set; }
    public DateTime? CRBCheckDate { get; set; }
    public DateTime? CMSTrainingDate { get; set; }
    public int? teamID { get; set; }

    public virtual tblPlussTeams Team { get; set; }

    [ForeignKey("staffID")]
    public ICollection<tblClientSchemeHistory> CaseWorker1Schemes { get; set; }
    [ForeignKey("staffID")]
    public ICollection<tblClientSchemeHistory> CaseWorker2Schemes { get; set; }
}
}

and

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CMS3.Model.DBTables
{
public class tblClientSchemeHistory
{
    [Key]

    public int clientSchemeHistoryID { get; set; }
    public int clientID { get; set; }
    public string SchemeName { get; set; }
    public DateTime? startDate { get; set; }
    public DateTime? endDate { get; set; }
    public int? wcID { get; set; }
    public string currentModule { get; set; }
    [ForeignKey("Caseworker1"), Column(Order = 1)]
    public int? caseWorker1ID { get; set; }
    [ForeignKey("Caseworker2"), Column(Order = 2)]
    public int? caseWorker2ID { get; set; }
    public int? LDID { get; set; }
    public int? MHID { get; set; }
    public int contractTypeID { get; set; }
    public int? FSFID { get; set; }
    public bool? hiddenFlag { get; set; }
    [ForeignKey("clientID")]
    public virtual tblClients Client { get; set; }
    [InverseProperty("CaseWorker1Schemes")]
    public virtual tblStaff Caseworker1 { get; set; }
    [InverseProperty("CaseWorker2Schemes")]
    public virtual tblStaff Caseworker2 { get; set; }
    //public virtual tblClients Client { get; set; }

}

}

Within the context we have to define that tblClientSchemeHistory.Caseworker1 and tblClientSchemeHistory.Caseworker2 both map to tblStaff.staffID

EF Context

..DbSet<tblStaff> Staff { get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<tblClientSchemeHistory>().HasOptional(b => b.Caseworker1).WithMany(a => a.CaseWorker1Schemes).HasForeignKey(b => b.caseWorker1ID);
        modelBuilder.Entity<tblClientSchemeHistory>().HasOptional(b => b.Caseworker2).WithMany(a => a.CaseWorker2Schemes).HasForeignKey(b => b.caseWorker2ID);
        modelBuilder.Entity<tblStaff>().HasKey(a => a.staffID);


    }

User Repository where the error occurs. When inspecting the newStaffRecord Object, staffID is set to 0, implying the database will deal with indexing the primary key. This exact call works with the same Db using our old application which uses an EDMX Diagram to map relationships.

UserRepository.cs

 bool ILoginRepository.CreateUser(string firstName, string lastName, DateTime securityTrainingDate, DateTime cRBCheckDate, DateTime cMSTrainingDate, string password, string email)
    {


        CMS3Context _db = new CMS3Context();
        string salt = null;

        string passwordHash = pwdManager.GeneratePasswordHash(password, out salt);

        var newStaffRecord = new tblStaff()
        {
            firstName = firstName,
            lastName = lastName,
            securityTrainingDate = securityTrainingDate,
            CRBCheckDate = cRBCheckDate,
            CMSTrainingDate = cMSTrainingDate,
            activeFlag = true,
            Alias = "",

            //TODO - these values should come from dropdowns that are fed in to this method
            contractorID = 1,
            teamID = null,
            fullName = firstName + " " + lastName

        };
        _db.Staff.Add(newStaffRecord);

        _db.SaveChanges();

        var newLoginRecord = new tblLogin()
        {
            staffID = 1,
            userName = firstName + "." + lastName,
            active = true,
            password = passwordHash,
            salt = salt,
            passwordChanged = DateTime.Now,
            failedLoginAttempts = 0
        };
        _db.Users.Add(newLoginRecord);
        _db.SaveChanges();


        return (true);
    }

Creating new records in different tables using the new application work fine, automatically indexing the PK.

Thanks for reading.