Monday, 23 October 2023

Enable Disable Identity Field to migrate data

CREATE TABLE [dbo].[AnIdentityTable](

       [Id] [int] IDENTITY(1,1) NOT NULL,

       [_Name] [nvarchar](50) NOT NULL,

 CONSTRAINT [PK_AnIdentityTable] PRIMARY KEY CLUSTERED

(

       [Id] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

GO

 

-- Enable insert values in the Identity Field

SET IDENTITY_INSERT [dbo].[AnIdentityTable] ON;

 

INSERT INTO [dbo].[AnIdentityTable] (Id, _Name)

VALUES (5, 'Some Value');

 

-- Disable insert values in the Identity Field, after disabling it starts frm the max value

SET IDENTITY_INSERT [dbo].[AnIdentityTable] OFF; 

Monday, 9 October 2023

Python to MSSQL

 import pandas as pd

import pyodbc
from sqlalchemy import create_engine # pip install SQLAlchemy
from sqlalchemy.engine import URL
import pypyodbc # pip install pypyodbc

# Database connection settings
server = 'serverName'
database = 'DB_Name'
username = 'un'
password = 'pw'


from sqlalchemy.types import (
    Boolean,
    Date,
    DateTime,
    Float,
    Integer,
    SmallInteger,
    String,
    Unicode,
    BigInteger,
)
def get_sqlalchemy_types(df_types):
    # dictionary mapping pandas dtypes to SQLAlchemy types
    dtype_to_sqlalchemy_type = {
        # 'int64': BigInteger,
        # 'float64': Float,
        'object': Unicode(length=255),
        # 'datetime64[ns]': DateTime
    }    
    # create an empty dictionary to store column names and SQLAlchemy types
    col_dict = {}    
    # loop through columns and add name and type to dictionary
    for col in df_types.columns:
        col_dtype = str(df_types[col].dtype)
        if col_dtype in dtype_to_sqlalchemy_type.keys():
            sqlalchemy_type = dtype_to_sqlalchemy_type[col_dtype]
            col_dict[col] = sqlalchemy_type
   
    return col_dict

conn_str = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};
                DATABASE={database};UID={username};PWD={password}'

conn = pyodbc.connect(conn_str)
connection_url = URL.create('mssql+pyodbc', query={'odbc_connect': conn_str})
enigne = create_engine(connection_url, module=pypyodbc)
result.to_sql('tablename', enigne, if_exists='append', index=False, schema='dbo',
dtype=get_sqlalchemy_types(result),
chunksize=100)
conn.close()

Wednesday, 4 October 2023