CREATE PROCEDURE [dbo].[usp_UpdateTableRecords]
-- Add the parameters for the stored procedure here
@TableName Varchar(100) = 'tbl_Name', -- Name of the Table
@Location Varchar(MAX) = 'C:\DBUpdate\Table\tbl_Name.csv' -- Excel File Location
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--Variable Declaration
DECLARE @ColName VARCHAR(MAX)
DECLARE @Condition as VARCHAR(MAX)
DECLARE @Var as VARCHAR(100)
DECLARE @Qry as VARCHAR(MAX)
DECLARE @ColumnName VARCHAR(MAX)
DECLARE @Condition1 as VARCHAR(MAX)
DECLARE @ColumnName1 VARCHAR(MAX)
DECLARE @FieldName VARCHAR(MAX)
SET @Condition = ''
SET @Condition1 = ''
SET @ColumnName1 = ''
-- Insert statements for procedure here
IF EXISTS(SELECT * FROM Sysobjects WHERE type = 'u' and name = 'tbl_TEMP1234')
DROP TABLE tbl_TEMP1234
SET @Qry = 'Select * into tbl_TEMP1234 from ' + @TableName + ' where 1 = 2'
EXEC (@Qry)
SET @Qry = 'Bulk Insert tbl_TEMP1234 From ''' + @Location + ''' WITH (FIELDTERMINATOR = '','',ROWTERMINATOR = ''\n'')'
EXEC (@Qry)
SELECT @ColName = Coalesce(@ColName,'') + KU.Column_name + ',' FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.Table_name = @TableName
IF(@colName <> '')
BEGIN
WHILE (@ColName != '')
BEGIN
SET @Var = (SELECT LTRIM(SUBSTRING(@Colname, 1,charindex(',', @Colname)-1)))
SET @Condition = @Condition + (@Var + ' Not in (SELECT ' + @Var + ' From ' + @TableName + ') and ')
SET @Condition1 = @Condition1 + (@TableName + '.' + @Var + ' = tbl_TEMP1234.'+ @Var + ' and ')
SET @ColName = (CASE WHEN (LEFT(@ColName, 1) != ',') THEN SUBSTRING(@ColName, charindex(',', @ColName) + 1, LEN(@ColName)) ELSE '' END)
END
SET @Condition = (SELECT Substring(@Condition, 1, Len(@Condition) - 4))
SET @Condition1 = (SELECT Substring(@Condition1, 1, Len(@Condition1) - 4))
SELECT @ColumnName = Coalesce(@ColumnName,'') + b.NAME + ',' FROM syscolumns b
INNER JOIN sysobjects a ON a.id = b.id AND a.TYPE = 'u' AND a.NAME = @TableName
SET @FieldName = @ColumnName
WHILE (@FieldName != '')
BEGIN
SET @Var = (SELECT LTRIM(SUBSTRING(@FieldName, 1,charindex(',', @FieldName)-1)))
SET @ColumnName1 = (@ColumnName1 + @TableName + '.' + @Var + ' = tbl_TEMP1234.'+ @Var + ',')
SET @FieldName = (CASE WHEN (LEFT(@FieldName, 1) != ',') THEN SUBSTRING(@FieldName, charindex(',', @FieldName) + 1, LEN(@FieldName)) ELSE '' END)
END
SET @ColumnName = (SELECT Substring(@ColumnName, 1, Len(@ColumnName) - 1))
SET @ColumnName1 = (SELECT Substring(@ColumnName1, 1, Len(@ColumnName1) - 1))
SET @Qry = ('UPDATE ' + @TableName + ' SET ' + @columnName1 + ' FROM tbl_TEMP1234 WHERE ' + @Condition1)
EXEC (@Qry)
SET @Qry = ('INSERT INTO ' + @TableName + '(' + @ColumnName + ')
SELECT * FROM tbl_TEMP1234 WHERE ' + @Condition)
EXEC (@Qry)
END
DROP TABLE tbl_TEMP1234
END
Similarly we can upload the file with any field and row Terminator