Get values from 2 Tables in different Databases into another table - sql

I have a Database for say MasterDB which has list of Some Databases Name in a Table tbl_B .Each DataBase Name is identified by an ID.
The structure of the table tbl_B is like the following
tbl_B
ID | DB_Name
-------------
1 | DelhiDB
2 | MumbaiDB
There are DataBases with the same name i.e DelhiDB and MumbaiDB and each of them have a Table with name tbl_C which will have some data for eg.
tbl_C for Delhi
custIDDelhi | custNameDelhi | CustPhoneDelhi |
----------------------------------------------
1 | John | 123456 |
2 | Monika | 789945 |
Please note here that the column names for Both the databases can be Different
Also Please note that DelhiDB and MumbaiDB are separate Database each having a table named tbl_C
I want to create a Table called tblCusotmer_Dictionary in MasterDB
With Data something like this
ColumnName | DataBaseName | DataBaseID | db_ColumnNamme
-----------------------------------------------------------
CustomerID | DelhiDB | 1 | custIDDelhi
CustomerName | DelhiDB | 1 | custNameDelhi
CustomerPhone | DelhiDB | 1 | CustPhoneDElhi
CustomerID | MumbaiDB | 2 | custIDMumbai
CustomerName | MumbaiDB | 2 | custNameMumbai
CustomerPhone | MumbaiDB | 2 | CustPhoneMumbai
Here I dont want any customer data just a list of column name from both the databases along with Database name and ID ,
the column ColumnName in the above table is the Generic Name I am giving to the column db_ColumnNamme
I have taken example for 2 databases and 3 columns for simplicity But there can can be N number for databases each having a table with a same name ( tbl_c here) with fixed no of columns.
Let me know in comments for any clarifications.

if I understood your question correctly then below is the solution which you are looking for. Let me know if it works for you.
DECLARE #tblDatabaseName AS TABLE (Id INT, dbName VARCHAR(100))
--DROP TABLE #tmpREcord
INSERT INTO #tblDatabaseName(id,dbName) VALUES (1,'DelhiDB'),(1,'MumbaiDB')
DECLARE #SQL AS VARCHAR(8000)
DECLARE #Id INT
DECLARE #dbName AS VARCHAR(100)
CREATE TABLE #tmpRecord (
columnName VARCHAR(20),DBID INT, DatabaseName VARCHAR(100))
DECLARE cur_Traverse CURSOR FOR SELECT Id , dbName FROM #tblDatabaseName
OPEN cur_Traverse
FETCH NEXT FROM cur_Traverse INTO #id ,#dbName
WHILE ##FETCH_STATUS =0
BEGIN
SET #SQL = 'INSERT INTO #tmpRecord (ColumnName,DbId,DatabaseName )
SELECT name ,' + CONVERT(VARCHAR(10),#Id) + ' AS DBID, ''' + #dbName + ''' as dbname'
+ ' FROM ' + #dbName + '.sys.all_columns s
WHERE object_Id = (SELECT TOP(1) object_Id FROM ' + #dbName + '.sys.all_objects WHERE name=''tbl_C'')'
PRINT #SQL
EXECUTE (#SQL)
FETCH NEXT FROM cur_Traverse INTO #Id, #dbName
END
CLOSE cur_Traverse
DEALLOCATE cur_Traverse
SELECT * FROM #tmpRecord

You appears to want :
select t.colsname as ColumnName,
b.db_name as DataBaseName,
b.id as DataBaseID,
t.cols as db_ColumnNamme
from tbl_C c
cross apply (values ('custID', 'CustomerID'), ('custName', 'CustomerName'),
('CustPhone', 'CustomerPhone')
) t (cols, colsname)
inner join tbl_B b on b.id = c.custID;

Related

Store any transaction in log table SQL Server

I have lots of tables in my SQL Server database. When any action happens, like an Insert, Update, Delete, I want to store the data in a Log table as shown here:
Product table:
| ID | Name | Other |
| --- | ------- | --- |
| 1 | Book | ... |
| 2 | Bicycle | ... |
If any Insert, Update or Delete happens, I want to have something like this:
Log table:
| ID | RowId | TableName | Action |
| --- | ------- | ---------- | ------ |
| 1 | 1 | Product | Insert |
| 2 | 2 | Product | Insert |
| 3 | 15 | Category | Update |
| 4 | 60 | Customer | Insert |
I'm using Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (X64) Express edition with Advanced Services - some features might not be available for me (reference to documentation).
For a single table a trigger is a good idea and it works fine, but what about all tables? As the example shows, Category and Customer tables are other tables in my database.
If your problem is the number of triggers, you should create; then create a job to create the trigger when a new table has been created. The below code checks the tables that have not that kind of triggers using specific formula of naming. In my example tablename plus '_dml_audit'. You can change it anyway.
Set NOCOUNT ON
select Concat (QUOTENAME(sch.name) , '.' , QUOTENAME(tbl.name)) TableNames
into #Tables
From sys.tables tbl
INNER JOIN sys.schemas sch on sch.schema_id = tbl.schema_id
LEFT JOIN sys.triggers trg on tbl.object_id = trg.parent_id and trg.name like tbl.name + '_dml_audit'
Where trg.object_id is null
GO
exec sp_MSforeachtable 'IF ''?'' IN (Select TableNames FROM #Tables) Begin PRINT ''?'' END'
Drop Table #Tables
For older version that does not support #table use this:
Create Table TempTable (TableNames sysname)
GO
Insert TempTable
SELECT Concat ('[', sch.name , '].[' , tbl.name, ']') TableNames
From sys.tables tbl
INNER JOIN sys.schemas sch on sch.schema_id = tbl.schema_id
LEFT JOIN sys.triggers trg on tbl.object_id = trg.parent_id and trg.name like tbl.name + '_dml_audit'
Where trg.object_id is null
GO
exec sp_MSforeachtable 'IF ''?'' IN (Select TableNames FROM TempTable) Begin PRINT ''?'' END'
GO
Drop Table TempTable
Replace Trigger Definition with the PRINT statement and Define a job for it.

Moving result from 1:n query to repeating columns

I would like to achieve the following from a result of a 1:n join using T-sql
Surname | Givename |..Address | City
Name1....| Givename1.|..Addr11...| City11
Name1....| Givename1.|..Addr12...| City12
Name2....| Givename2.|..Addr21...| City21
Name2....| Givename2.|..Addr22...| City22
Name2....| Givename2.|..Addr23...| City23
TO:
Surname | Givename.. | Address | City... | Address | City... | Address | City
Name1....| Givename1...| Addr11....| City11. | Addr12....| City12. |
Name2....| Givename2...| Addr21....| City21. | Addr22....| City22. | Addr23....| City23
I not care about repeating columnames. Up if there is a soultion with numbers in the repeating columns it would be fine too.
Thanks
In my opinion Pivot is not a solution in this case. Because the column name should repat, and in pivot, cell values are moved to column names, also is unlike pivot no aggregate function involved.
In my thought, the following query will handle your issue. However the SQL Server has column number limit for tables.
Columns per table 1,024 Tables that include sparse column sets
include up to 30,000 columns. See sparse column sets.
You should take this considiration for your data.
DROP TABLE IF EXISTS #Test
DROP TABLE IF EXISTS ##PivotUnlimited
CREATE TABLE #Test(Surname VARCHAR(100) , GivenName VARCHAR(200),
Adress VARCHAR(100),City VARCHAR(100))
INSERT INTO #Test
VALUES
('Name1','Givename1','Addr11','City11'),
('Name1','Givename1','Addr12','City12'),
('Name2','Givename2','Addr21','City21'),
('Name2','Givename2','Addr22','City21'),
('Name2','Givename2','Addr23','City23')
,('Name5','Givename5','Addr51','City51'),
('Name5','Givename5','Addr52','City52'),
('Name5','Givename5','Addr53','City53'),
('Name5','Givename5','Addr54','City54'),
('Name3','Givename3','Addr31','City31')
DECLARE #Counter AS INT=1
DECLARE #Max AS INT
DECLARE #SQL AS VARCHAR(MAX)
SELECT #Max= MAX(DetMax) FROM
(
SELECT ROW_NUMBER() OVER(Partition by Surname ORDER BY Surname ) AS DetMax FROM #Test
) AS TMP
DROP TABLE IF EXISTS ##PivotUnlimited
CREATE TABLE ##PivotUnlimited (Surname VARCHAR(100),GivenName VARCHAR(100))
WHILE #Counter <=#Max
BEGIN
SET #SQL= 'ALTER TABLE ##PivotUnlimited ADD ADDR' + CONVERT(VARCHAR,#Counter) + ' VARCHAR(100)'
EXEC(#SQL)
SET #SQL= 'ALTER TABLE ##PivotUnlimited ADD City' + CONVERT(VARCHAR,#Counter) + ' VARCHAR(100)'
EXEC(#SQL)
SET #Counter=#Counter+1
END
INSERT INTO ##PivotUnlimited (Surname,GivenName)
SELECT DISTINCT Surname , GivenName FROM #Test
DECLARE #Name AS VARCHAR(100)
DECLARE cursorT CURSOR
FOR
SELECT DISTINCT Surname from #test
OPEN cursorT
FETCH NEXT FROM cursorT INTO #Name
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #CounterCursor AS INT=1
DECLARE #MaxCursort AS INT =0
DECLARE #UpdateSQL AS VARCHAR(MAX)
DECLARE #UptAdr AS VARCHAR(100)
DECLARE #UptCity AS VARCHAR(100)
SELECT #MaxCursort=RowNumber FROM (
SELECT ROW_NUMBER() OVER(Partition by Surname ORDER BY Surname ) AS RowNumber FROM #Test
WHERE Surname=#Name
) AS TMP_TBL
WHILE #CounterCursor<= #MaxCursort
BEGIN
SELECT #UptAdr=Adress ,#UptCity=City FROM (
SELECT ROW_NUMBER() OVER(Partition by Surname ORDER BY Surname ) AS RowNumber,* FROM #Test
) AS TMP_TBL WHERE RowNumber=#CounterCursor and Surname=#Name
SET #UpdateSQL= 'UPDATE ##PivotUnlimited SET ADDR' + CONVERT(VARCHAR,#CounterCursor) + ' = ' + '''' + #UptAdr +'''' + ' , '
+ ' City' + CONVERT(VARCHAR,#CounterCursor) + ' = ' + '''' + #UptCity +'''' + ' WHERE Surname = ' + '''' + #Name + ''''
EXEC (#UpdateSQL)
SET #CounterCursor=#CounterCursor+1
END
FETCH NEXT FROM cursorT INTO #Name
END
CLOSE cursorT
DEALLOCATE cursorT
SELECT * FROM ##PivotUnlimited
+---------+-----------+--------+--------+--------+--------+--------+--------+--------+--------+
| Surname | GivenName | ADDR1 | City1 | ADDR2 | City2 | ADDR3 | City3 | ADDR4 | City4 |
+---------+-----------+--------+--------+--------+--------+--------+--------+--------+--------+
| Name1 | Givename1 | Addr11 | City11 | Addr12 | City12 | NULL | NULL | NULL | NULL |
| Name2 | Givename2 | Addr21 | City21 | Addr22 | City21 | Addr23 | City23 | NULL | NULL |
| Name3 | Givename3 | Addr31 | City31 | NULL | NULL | NULL | NULL | NULL | NULL |
| Name5 | Givename5 | Addr51 | City51 | Addr52 | City52 | Addr53 | City53 | Addr54 | City54 |
+---------+-----------+--------+--------+--------+--------+--------+--------+--------+--------+

Execute stored procedure with parameter from other table

I have a procedure with one parameter, letsay #AssetID int.
I want to select a column value from another table, then use that value as the parameter for this procedure.
I've stored procedure something like this and the table has been filtered with "Where" criteria from #AssetID parameter:
declare #inspectyear as nvarchar(max), #calc as nvarchar(max), #query as nvarchar(max);
set #inspectyear = STUFF((select distinct ',' + quotename(InspectYear) from ##t2 c
for XML path(''), type).value('.','NVARCHAR(MAX)'),1,1,'')
select #calc = ', ' + quotename(Max(InspectYear)) + ' - ' + quotename(Max(InspectYear)-2)
+ ' as Calc1, ' + quotename(Max(InspectYear)) + ' - ' + quotename(min(InspectYear))
+ ' as Calc2' from #t2;
set #query =
';with data as
(
select inspectyear,
partno, Pos, number
from #t2
unpivot
(
number
for Pos in ([Pos1], [Pos2], [Pos3], [Pos4])
) unpvt
)
select * ' + #calc + ' into ##temp
from data
pivot
(
sum(number)
for inspectyear in (' + #inspectyear + ')
) pvt
order by partno';
exec sp_executesql #query = #query;
select * from ##temp;
drop table ##temp;
So I need to create another procedure, for instance:
create procedure spExecmyProc
as
begin
exec spMyProc '#AssetID' -- <-- The parameter took from other table.
go
end
The #date parameter, took from other table.
Is it possible to do that? The result should be only one result.
So far, this is what I did. It works, but the result is not on "one result". It create more than one result if the #AssetID is more than one:
declare #AssetID int;
declare cur CURSOR FOR
select distinct AssetID from myTable
open cur
fetch next from cur into #AssetID
while ##FETCH_STATUS = 0
begin
exec mySPName #AssetID
fetch next from cur into #AssetID
end
close cur
DEALLOCATE cur
Thank you.
I'm not 100% sure I understand what you're trying to achieve, but if you want to be able to be able to run some code on each value of AssetID in mytable, returning just one result for each input value, I think you could use a Scalar-valued Function. Let's pretend that the purpose of your original stored procedure was just to increment the AssetId value by 1 for simplicity - your function could be created like this:
CREATE FUNCTION fnMyFunction (#AssetId INT)
RETURNS INT
AS
BEGIN
DECLARE #return INT
SET #return = #AssetId + 1
RETURN #return
END
If you then have some values in a table:
CREATE TABLE Assets (
AssetId INT
)
INSERT INTO Assets
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 5
UNION
SELECT 7
UNION
SELECT 5
You can call your function on each value you return:
SELECT AssetId,
dbo.fnMyFunction(AssetId) AS AssetIdPlus1
FROM Assets
Which gives these results for my super simple dataset defined above:
/------------------------\
| AssetId | AssetIdPlus1 |
|---------+--------------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 5 | 6 |
| 7 | 8 |
| 5 | 6 |
\------------------------/
If you just want to get the result for each unique value of AssetId in your table, then just return the DISTINCT results:
SELECT DISTINCT
AssetId,
dbo.fnMyFunction(AssetId)
FROM Assets
which would give these results for the same dataset above (with just one row for AssetId = 5):
/------------------------\
| AssetId | AssetIdPlus1 |
|---------+--------------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 5 | 6 |
| 7 | 8 |
\------------------------/

Taking a SUM of a text field representing a column name in postgres

Here's a sample of my table
[myTable]
id | random1 | random2 | random3 | random4
1 | 123 | 5357 | 10 | 642
2 | 423 | 34 | 20 | 531
3 | 9487 | 234 | 30 | 975
4 | 34 | 123 | 40 | 864
Here's my current query, but it isn't working like I'd expect it to:
SELECT
cols.*,
(SELECT SUM(cols.column_name) FROM myTable t)
FROM
(SELECT
table_name::text, column_name::text
FROM
information_schema.columns
where
table_name = 'myTable') as cols
I'm getting the error: function sum(text) does not exist - which makes sense. I'm pretty sure that mysql is can be messy enough to allow a reference like that, but I don't know how to do this in postgres.
What I'd really like to have is an end result somewhere along the lines of...
table_name | column_name | sum
myTable | id | 10
myTable | random1 | 10067
myTable | random2 | 5748
myTable | random3 | 100
myTable | random4 | 3012
I want to take this query a lot further, but I'm getting really hung up on being able to reference the column name.
SQL queries are static. They select before-known columns from before-known tables. You cannot make them look up table names and columns from the database dictionary and then magically glue these names into themselves.
What you can do: Write a program (Java, C#, PHP, whatever you like) doing the following:
Send a query to the DBMS to find the column names for the table you are interested in.
Build a SQL query string with the column names got.
Send this query to the DBMS.
declare #tableName varchar(255) = 'myTable' --Change this to the table name you want
/*create table and column name dataSet and insert values*/
if object_id('tempdb.dbo.#objectSet') is not null
drop table #objectSet
create table #objectSet
(table_name varchar(256),
columnID int,
column_name varchar(256),
[sum] int)
insert into #objectSet
(table_name,
columnID,
column_name)
select O.name table_name,
C.column_id columnID,
C.name column_name
from sys.all_objects O
join sys.all_columns C
on O.object_id = C.object_id
join sys.types T
on C.user_type_id = T.user_type_id
where O.object_id = object_id(#tableName)
and T.name in ('int', 'tinyint', 'smallint', 'bigint') --Columns with Aggregatable datatypes only, all other columns will be excluded from the set.
/*Create loop variables for each column*/
declare #SQL as varchar(4000),
#counter int = 1,
#maxCount int
select #maxCount = SQ.maxCount
from ( select count(*) maxCount
from #objectSet OS) SQ
/*Run loop, updating each column as it goes*/
while #counter <= #maxCount
begin
select #SQL = 'update OS set OS.[sum] = SQ.[sum] from #objectSet OS join (select sum(DS.' + OS.column_name + ') [sum] from ' + #tableName + ' DS) SQ on OS.column_name = ''' + OS.column_name + ''''
from #objectSet OS
where OS.columnID = #counter
exec (#SQL)
select #counter += 1
end
/*Display Results*/
select OS.table_name,
OS.column_name,
OS.[sum]
from #objectSet OS
Using system object tables, some dynamic T-SQL, and a loop should do it.

SQL Column Names from a Excel Sheet

Im using SSMS 2014 and SQL Server 2014. I need to change the column names at the end of a query result by using a excel file or table with the data.
After some SELECT statements and stuff i get a table with data for example
+---------+---------+------+
| Col1 | Col2 | Col3 |
+---------+---------+------+
| Value 1 | Value 2 | 123 |
| Value 2 | Value 2 | 456 |
| Value 3 | Value 3 | 789 |
+---------+---------+------+
And the table or excelfile
+----+---------+-----------+-----------+
| ID | ColName | Language | Addition |
+----+---------+-----------+-----------+
| 1 | Col1 | D | 123 |
| 2 | Col2 | D | 456 |
| 3 | Col3 | D | 789 |
| 4 | Col1 | E | 123 |
| 5 | Col2 | E | 456 |
| 6 | Col3 | E | 789 |
+----+---------+-----------+-----------+
What i try to do is to get the addition value of each column and add it to the column name. It should only add the values with the specific language. #setLang = 'D'
Col1 + Addition
Col2 + Addition
Col3 + Addition
+-------------+-------------+---------+
| Col1 123 | Col2 456 | Col3789 |
+-------------+-------------+---------+
| Value 1 | Value 2 | 123 |
| Value 2 | Value 2 | 456 |
| Value 3 | Value 3 | 789 |
+-------------+-------------+---------+
I tried it over Information_Schema.Columns and filter with where table = 'resultTable' and Column_name = #cName. Maybe i need a loop to get each columnname.
Thanks for reading and trying to help me.
Give this a go - it uses a table, not an excel file (but that seems to be an option in your question). I have made some temporary tables and filled them with your values, but you will obviously not need to do this. You will need to replace out the references to the tempdb with the name of the database where your tables are kept and the temp tables #Original and #ExcelInfo with your table names.
I have also used a temp table to add an 'Id IDENTITY(1,1)` Column to the table holding your original data. This is needed to keep the unpivot in check; if you can modify your table to include an Id, that will make things easier, but if not, you can insert into a temp table as I have done.
The script is shorter than it looks - the whole first bit is just setting up the example; the real answer starts at the line that declares your language variable.
/*
The script between the first two dividing lines of dashes is just used to set up the example. The bit you want is from
the "-- Test Variables --" line.
*/
-----------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb..#Original') IS NOT NULL DROP TABLE #Original
IF OBJECT_ID('tempdb..#ExcelInfo') IS NOT NULL DROP TABLE #ExcelInfo
CREATE TABLE #Original
( Col1 VARCHAR(50)
,Col2 VARCHAR(50)
,Col3 VARCHAR(50))
CREATE TABLE #ExcelInfo
( Id INT IDENTITY(1,1) NOT NULL
,ColName VARCHAR(50) NOT NULL
,[Language] CHAR(1) NOT NULL
,Addition INT NOT NULL)
INSERT #Original
SELECT *
FROM
( SELECT 'Value 1' AS Col1,'Value 2' AS Col2 ,123 AS Col3
UNION SELECT 'Value 2' ,'Value 2' ,456
UNION SELECT 'Value 3' ,'Value 3' ,789) AS This
ORDER BY Col1
INSERT #ExcelInfo (ColName,[Language],Addition)
SELECT *
FROM
( SELECT 'Col1' AS ColName, 'D' AS [Language], 123 AS Addition
UNION SELECT 'Col2','D',456
UNION SELECT 'Col3','D',789
UNION SELECT 'Col1','E',123
UNION SELECT 'Col2','E',456
UNION SELECT 'Col3','E',789) AS This
ORDER BY [Language], Addition
-----------------------------------------------------------------------------------------------------------------------
-- Test Variables --
DECLARE #SetLang CHAR(1) = 'D'
-----------------------------------------------------------------------------------------------------------------------
-- make the default empty, not null on our dynamic string, so it can be added to
DECLARE #Columns VARCHAR(MAX) = ''
DECLARE #SQL VARCHAR(MAX)
CREATE TABLE #OriginalColumns
( Id INT IDENTITY(1,1)
,Name VARCHAR(50))
CREATE TABLE #BasicResult
(Id INT NOT NULL, Name VARCHAR(50), Value VARCHAR(50))
-- If you can add an id column to your original table, this bit is unecessary - you can use yours in place of this table
CREATE TABLE #Original_WITH_Id
( Id INT IDENTITY(1,1)
,Col1 VARCHAR(50)
,Col2 VARCHAR(50)
,Col3 VARCHAR(50))
INSERT #Original_WITH_Id
SELECT * FROM #Original
-----------------------------------------------------------------------------------------------------------------------
-- List out the columns and put the list in a variable.
INSERT #OriginalColumns
SELECT QUOTENAME(Col.name)
FROM tempdb.sys.columns AS Col
WHERE Col.object_id = OBJECT_ID('tempdb.dbo.#Original_WITH_Id')
-- we're not interested in the identity column at the moment
AND Col.name <> 'Id'
-- keep everything in the same order as they are listed on the table
ORDER BY Col.column_id
SELECT #Columns = #Columns + ',' + Name
FROM #OriginalColumns
-- clip off the leading comma
SELECT #Columns = SUBSTRING(#Columns,2,LEN(#Columns))
-- get a full list of everything, creating our new list of columns as we go, using the Id column to keep a mark on which
-- row each record originally came from
SET #SQL =
'INSERT #BasicResult
SELECT Id, New.Name, Value FROM
(SELECT Id, Name, Value
FROM #Original_WITH_Id
UNPIVOT (Value FOR Name IN (' + #Columns + ')) Unpvt) AS Old
JOIN (SELECT ColName, CONVERT(VARCHAR(50),ColName) + '' '' + CONVERT(VARCHAR(50),Addition) AS Name
FROM #ExcelInfo
WHERE [Language] = ''' + #SetLang + ''') AS New ON Old.Name = New.ColName'
PRINT #SQL
EXEC (#SQL)
-- now update our list of columns to be the new column headings
SET #Columns = ''
SELECT #Columns = #Columns + ',' + QUOTENAME(Name) FROM (SELECT DISTINCT Name FROM #BasicResult) AS Names
SELECT #Columns = SUBSTRING(#Columns,2,LEN(#Columns))
-- pivout our results back out to their original format, but with the new column headings (include the Id if you want)
SET #SQL =
'SELECT /*Id,*/ ' + #Columns + '
FROM
(SELECT Id, Name,Value
FROM #BasicResult) AS Up
PIVOT (MAX(Value) FOR Name IN (' + #Columns + ')) AS Pvt'
PRINT #SQL
EXEC (#SQL)
-- clean up --
DROP TABLE #OriginalColumns
DROP TABLE #BasicResult
Hope that helps! There may be a more efficient way to do this... I'm not sure.
Okay i tried it again but now without the Excelfile. I made a CSV out of the Excelfile and insert it with Bulk to my created Table:
IF NOT EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CSVTest')
BEGIN
CREATE TABLE _DICTIONARY
( _TableName VARCHAR (20),
_ColumnName VARCHAR (20),
_Language VARCHAR (20),
_FieldShort VARCHAR (50),
_FieldMid VARCHAR (50),
_FieldLong VARCHAR (50)
)
BULK
INSERT _DICTIONARY
FROM 'C:\_DICTIONARY.csv'
WITH
(
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)
END
After that i rename all Columns by using a Cursor
DECLARE #dic_tableName as nvarchar(50),
#dic_columnName as nvarchar(50),
#db_tableName as nvarchar(50),
#db_columnName as nvarchar(50);
DECLARE C CURSOR FAST_FORWARD FOR
SELECT _TableName, _ColumnName FROM _DICTIONARY
OPEN C;
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
WHILE ##FETCH_STATUS = 0
BEGIN
IF EXISTS(SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #dic_tableName AND COLUMN_NAME = #dic_columnName)
BEGIN
SET #db_tableName = #dic_tableName + '.' + #dic_columnName
SET #db_columnName = #dic_tableName + '_' + #dic_columnName
EXEC sp_rename #db_tableName, #db_columnName ,'COLUMN'
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
END
ELSE
BEGIN
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
END
END
CLOSE C;
DEALLOCATE C;
Its doing its job.