CREATE PROC [dbo].[usp_InsertGenerator]
AS
BEGIN
DECLARE #tablename varchar(max)
DECLARE cursCol1 CURSOR FOR
SELECT name FROM sys.tables
OPEN cursCol1
FETCH NEXT FROM cursCol1 INTO #tablename
DECLARE cursCol CURSOR FOR
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = #tableName
OPEN cursCol
DECLARE #string nvarchar(3000)
DECLARE #stringData nvarchar(3000)
DECLARE #dataType nvarchar(1000)
SET #string='INSERT '+#tableName+'('
SET #stringData=''
DECLARE #colName nvarchar(50)
FETCH NEXT FROM cursCol INTO #colName,#dataType
IF ##fetch_status<>0
BEGIN
PRINT 'Table '+#tableName+' not found, processing skipped.'
--FETCH NEXT FROM cursCol1 INTO #tablename
CLOSE curscol
DEALLOCATE curscol
RETURN
END
WHILE ##FETCH_STATUS=0
--FETCH NEXT FROM cursCol1 INTO #tablename
BEGIN
IF #dataType in ('varchar','char','nchar','nvarchar')
BEGIN
SET #stringData=#stringData+'''''''''+
isnull('+#colName+','''')+'''''',''+'
END
ELSE
BEGIN
SET #stringData=#stringData+'''''''''+
isnull(cast('+#colName+' as varchar(200)),''0'')+'''''',''+'
END
SET #string=#string+#colName+','
FETCH NEXT FROM cursCol INTO #colName ,#dataType
END
BEGIN
DECLARE #Query nvarchar(4000)
SET #query ='SELECT '''+substring(#string,0,len(#string)) + ')
VALUES(''+ ' + substring(#stringData,0,len(#stringData)-2)+'''+'')''
FROM '+#tableName
PRINT (#query)
CLOSE cursCol1
DEALLOCATE cursCol1
CLOSE cursCol
DEALLOCATE cursCol
END
END
GO
When executing the procedure I am only getting first value(Row) from name column in sys.tables.
I want it for all the rows in the sys.tables.
Query should take each table name one by one then execute the query for every table so that I can get insert statement for all the tables.
Thanks in advance .
Please try using cursor to get name, cursCol1 Should be closed at last after cursCol. FETCH NEXT is also missing for cursCol1
CREATE PROC [dbo].[usp_InsertGenerator]
AS
BEGIN
DECLARE #tablename varchar(max)
DECLARE #tbl table (insertVal varchar(max))
DECLARE cursCol1 CURSOR FOR
SELECT name FROM sys.tables
OPEN cursCol1
FETCH NEXT FROM cursCol1 INTO #tablename
WHILE ##FETCH_STATUS=0
begin
DECLARE cursCol CURSOR FOR
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = #tableName
OPEN cursCol
DECLARE #string nvarchar(3000)
DECLARE #stringData nvarchar(3000)
DECLARE #dataType nvarchar(1000)
SET #string='INSERT '+#tableName+'('
SET #stringData=''
DECLARE #colName nvarchar(50)
FETCH NEXT FROM cursCol INTO #colName,#dataType
IF ##fetch_status<>0
BEGIN
PRINT 'Table '+#tableName+' not found, processing skipped.'
FETCH NEXT FROM cursCol1 INTO #tablename
CLOSE curscol
DEALLOCATE curscol
RETURN
END
WHILE ##FETCH_STATUS=0
--FETCH NEXT FROM cursCol1 INTO #tablename
BEGIN
IF #dataType in ('varchar','char','nchar','nvarchar')
BEGIN
SET #stringData=#stringData+'''''''''+
isnull('+#colName+','''')+'''''',''+'
END
ELSE
BEGIN
SET #stringData=#stringData+'''''''''+
isnull(cast('+#colName+' as varchar(200)),''0'')+'''''',''+'
END
SET #string=#string+#colName+','
FETCH NEXT FROM cursCol INTO #colName ,#dataType
END
BEGIN
DECLARE #Query nvarchar(4000)
SET #query ='SELECT '''+substring(#string,0,len(#string)) + ')
VALUES(''+ ' + substring(#stringData,0,len(#stringData)-2)+'''+'')''
FROM '+#tableName
INSERT INTO #tbl (insertVal) EXEC (#query)
-- PRINT (#query)
END
CLOSE cursCol
DEALLOCATE cursCol
FETCH NEXT FROM cursCol1 INTO #tablename
END
CLOSE cursCol1
DEALLOCATE cursCol1
SELECT * FROM #tbl
END
Related
I'm trying to update all table based on my value. This is a script Task in my SSIS package.
But I get the error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
Code looks like this:
DECLARE #Column_name varchar(MAX)
DECLARE #Column_Datatype varchar(max)
SET #COLUMN_NAME='site_id'
SET #COLUMN_DATATYPE='varchar(10)'
------------------------------------------------Code---------------------------------------------------
GO
--Declare Variables
DECLARE #TableName VARCHAR(100)
DECLARE #TableSchema VARCHAR(100)
DECLARE #COLUMN_NAME VARCHAR(50)
DECLARE #COLUMN_NAME_UPDATE VARCHAR(50)
SET #COLUMN_NAME_UPDATE = ?
SET #COLUMN_NAME='site_id'
DECLARE #COLUMN_DATATYPE VARCHAR(50)
SET #COLUMN_DATATYPE='varchar(max)'
--Declare Cursor
DECLARE CUR CURSOR FOR
SELECT TABLE_SCHEMA,
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
--OPEN CURSOR
OPEN CUR
--Fetch First Row
FETCH NEXT FROM CUR INTO #TableSchema,#TableName
--Loop
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #SQL NVARCHAR(MAX)
SET #SQL= ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=#TableName AND COLUMN_NAME=#COLUMN_NAME
and Table_Schema=#TableSchema)
BEGIN
SET #SQL='UPDATE '+ #TableSchema+'.'+ '[' + #TableName + ']' + ' SET '+#COLUMN_NAME + '='
+ '''' + #COLUMN_NAME_UPDATE + '''' + 'WHERE site_id IS NULL '
PRINT #SQL
EXEC ( #SQL)
END
FETCH NEXT FROM CUR INTO #TableSchema,#TableName
END
--Close and Deallocate Cursor
CLOSE CUR
DEALLOCATE CUR
I use a variable like input.
What's wrong?
I understand that you can set a default fill factor but I want to change existing fill factors back to default across an entire server.
DECLARE #Database VARCHAR(255)
DECLARE #Table VARCHAR(255)
DECLARE #cmd NVARCHAR(500)
DECLARE #fillfactor INT
SET #fillfactor = 90
DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','msdb','tempdb','model','distribution')
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO #Database
WHILE ##FETCH_STATUS = 0
BEGIN
SET #cmd = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM [' + #Database + '].INFORMATION_SCHEMA.TABLES
WHERE table_type = ''BASE TABLE'''
-- create table cursor
EXEC (#cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO #Table
WHILE ##FETCH_STATUS = 0
BEGIN
IF (##MICROSOFTVERSION / POWER(2, 24) >= 9)
BEGIN
-- SQL 2005 or higher command
SET #cmd = 'ALTER INDEX ALL ON ' + #Table + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),#fillfactor) + ')'
EXEC (#cmd)
END
ELSE
BEGIN
-- SQL 2000 command
DBCC DBREINDEX(#Table,' ',#fillfactor)
END
FETCH NEXT FROM TableCursor INTO #Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO #Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
BEGIN TRAN
DECLARE #table_name VARCHAR(MAX)
DECLARE table_cursor CURSOR LOCAL
FOR
SELECT
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO
#table_name
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'ALTER INDEX ALL ON '+#table_name+'
REBUILD WITH (FILLFACTOR = 100)'
END
CLOSE table_cursor;
DEALLOCATE table_cursor;
ROLLBACK TRAN
I am not an SQL Expertise. I need to search for the column which is present in all the tables of the database but which does not has null values stored for that specific record.
Below is the query that fetches me all the tables that has my column name:
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name LIKE 'classPK'
Try this...
declare #q nvarchar(1000);
declare cur_Select cursor for
select 'select * from ['+tab.name+'] where ['+col.name+'] is not null'
from sys.tables tab
join sys.columns col
on tab.object_id = col.object_id
where col.name like 'name'
open cur_Select
fetch next from cur_Select into #q
while ##FETCH_STATUS = 0
begin
exec sp_executesql #q
fetch next from cur_Select into #q
end
close cur_Select
deallocate cur_Select
Try with this statement:
DECLARE #TABLE_NAME NVARCHAR(MAX);
DECLARE #COLUMN_NAME NVARCHAR(MAX);
DECLARE #crs CURSOR;
DECLARE #query NVARCHAR(MAX);
set #crs = CURSOR FOR
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name LIKE 'CD_CIC_PROD%'
BEGIN TRY
OPEN #crs
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM #crs INTO
#TABLE_NAME, #COLUMN_NAME
WHILE (##FETCH_STATUS = 0)
BEGIN
set #query = 'SELECT * FROM ['+#TABLE_NAME+'] WHERE ['+#COLUMN_NAME+'] IS NOT NULL'
EXEC sp_executesql #query
FETCH NEXT FROM #crs INTO
#TABLE_NAME, #COLUMN_NAME
END
I need to Copy a Company in NAV Database to another Company in Different Database with SQL Query. I have achived this using the code below, but if the Structure is different in the Source or Destination my code fails. Please help me in modifying it, so i can copy the Structure and Data from the Source and replace Data and Structure in the Destination.
The code is given below.
-- =============================================
-- Author: Prajeesh
-- Create date: 31.03.2015
-- Description: Function for copying comany from one database to another
-- =============================================
Create PROCEDURE [dbo].[sp_NAVCopyCompany_v2]
#sourcecompany varchar(max),
#targetdb varchar(max),
#targetcompany varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #tablename varchar(1000)
declare #columns varchar(max)
declare #columnname varchar (max)
declare #targettable varchar (max)
declare #isidentity int
declare #sqlcommand nvarchar (max) = 'select name from '+#targetdb+'.sys.all_objects where type=''U'' and object_id>0 and name like '''+#sourcecompany+'$%'''
declare #sqlcommandIdentity nvarchar (max)
declare #tablevar table(name varchar(300))
declare #columntablevar table(COLUMN_NAME varchar(300))
declare #identitytablevar table(C int)
insert into #tablevar(name) exec sp_executesql #sqlcommand
DECLARE table_cursor CURSOR for
select name from #tablevar
OPEN table_cursor
FETCH NEXT FROM table_cursor
INTO #tablename
WHILE ##FETCH_STATUS = 0
BEGIN
--RAISERROR (#tablename, 0, 1) WITH NOWAIT
set #sqlcommand = 'SELECT COLUMN_NAME FROM '+#targetdb+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '''+#tablename+''' and COLUMN_NAME <> ''timestamp'''
DELETE from #columntablevar
insert into #columntablevar(COLUMN_NAME) exec sp_executesql #sqlcommand
DECLARE column_cursor CURSOR for select COLUMN_NAME from #columntablevar
select #columns=''
OPEN column_cursor
FETCH NEXT from column_cursor
INTO #columnname
WHILE ##FETCH_STATUS=0
BEGIN
SELECT #columns=#columns+',['+#columnname+']'
FETCH NEXT from column_cursor
INTO #columnname
END
CLOSE column_cursor;
DEALLOCATE column_cursor;
select #columns = SUBSTRING(#columns,2,LEN(#columns)-1)
--RAISERROR (#columns, 0, 1) WITH NOWAIT
select #targettable= #targetdb+'.dbo.['+#targetcompany+SUBSTRING(#tablename,LEN(#sourcecompany)+1,LEN(#tablename)-LEN(#sourcecompany)+1)+']'
--
select #isidentity=COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =#tablename AND COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
--
set #sqlcommandIdentity = 'SELECT COUNT(*) as C FROM '+#targetdb+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='''+#tablename+''' AND COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, ''IsIdentity'') = 1'
DELETE from #identitytablevar
insert into #identitytablevar(C) exec sp_executesql #sqlcommandIdentity
select #isidentity=SUM(C) FROM #identitytablevar
RAISERROR (#targettable, 0, 1) WITH NOWAIT
set #sqlcommand = ''
IF (#isidentity>0)
set #sqlcommand = #sqlcommand + 'SET IDENTITY_INSERT '+#targettable+' ON;'
set #sqlcommand = #sqlcommand + 'delete from '+#targettable+';'
set #sqlcommand = #sqlcommand + 'insert into '+#targettable+ ' ('+ #columns + ')'
+ ' select '+#columns
+ ' from ['+#tablename+']'
IF (#isidentity>0)
set #sqlcommand = #sqlcommand + ';SET IDENTITY_INSERT '+#targettable+' OFF'
--RAISERROR (#sqlcommand, 0, 1) WITH NOWAIT
exec sp_executesql #sqlcommand
FETCH NEXT FROM table_cursor
INTO #tablename
END
CLOSE table_cursor;
DEALLOCATE table_cursor;
END
The Query is called as
use SourceDatabase
exec sp_NAVCopyCompany_v2 'Source Company_','Destination Database','Destination Company'
I'm trying to create function on every database while I'm on master,
I'm using cursors
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name NOT IN('master','model','msdb','tempdb','ReportServer$SQLEXPRESS','ReportServer$SQLEXPRESSTempDB')
OPEN c_db_names
FETCH next from c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
set #sql = 'Create function...'
set #UseAndExecStatment = 'use ' + #db_name + ' exec sp_executesql '+#sql
exec Sp_executeSql #UseAndExecStatment
FETCH next from c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
the problem is that its not working, it says:
"CREATE FUNCTION' must be the first statement in a query batch"
Any ideas?
Thanks for your help.
You can use db..sp_executesql instead:
declare #sql nvarchar(max), #db_name nvarchar(max), #sql2 nvarchar(max)
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name NOT IN('master','model','msdb','tempdb','ReportServer$SQLEXPRESS','ReportServer$SQLEXPRESSTempDB')
and name ='reports'
OPEN c_db_names
FETCH next from c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
set #sql2 = 'create procedure ...'
set #sql = 'exec '+#db_name+'..sp_executesql N''' + #sql2+''''
print #sql
--exec(#sql)
FETCH next from c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
define the database in "create" query
try
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name NOT IN('master','model','msdb','tempdb','ReportServer$SQLEXPRESS','ReportServer$SQLEXPRESSTempDB')
OPEN c_db_names
FETCH next from c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
set #sql = 'Create function '+#db_name+'dbo.functionName ......'
exec Sp_executeSql #sql
FETCH next from c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
see:
set #sql = 'Create function '+#db_name+'dbo.functionName ......'
done :)
declare #sql nvarchar(max), #db_name nvarchar(max), #sql2 nvarchar(max)
declare #sp_executesql nvarchar (max)
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name NOT IN('master','model','msdb','tempdb','ReportServer$SQLEXPRESS','ReportServer$SQLEXPRESSTempDB')
--and name ='reports'
OPEN c_db_names
FETCH next from c_db_names INTO #db_name
WHILE ##Fetch_Status = 0
BEGIN
set #sql2 = N'
CREATE FUNCTION [String_Turn_Month] (#d char(6))
RETURNS char(6)
AS
BEGIN
DECLARE ##DSTR char(6)
IF #D=''''000000''''
set ##dstr=''''000000''''
IF substring(#d,3,4)<1800
RETURN(#D)
IF substring(#d,3,4)>1800
set ##dstr=cast(substring(#d,3,4)+substring(#d,1,2) as char(6))
RETURN(##DSTR)
END'
-- set #sql = 'exec '+#db_name+'..sp_executesql N''' + #sql2+''''
set #sp_executesql = 'exec ' + #db_name + '..sp_executeSQL N''' + #sql2 + ''''
PRINT #sp_executesql
EXEC sp_executeSQL #sp_executesql
print '------------'
print '------------'
print '------------'
-- exec(#sql)
FETCH next from c_db_names INTO #db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names