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.