SQL Server Stored Procedure for multiple excel file load [closed] - sql-server

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Please help me is their procedure available to use for multiple Excel files load into SQL Server table.
I found one on google, but not working as expected:
Msg 111, Level 15, State 1, Procedure usp_ImportMultipleFiles, Line 11 [Batch Start Line 40]
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 137, Level 15, State 2, Line 67
Must declare the scalar variable "#filepath".
1a. Create a table for getting file names
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = '[FileNames]')
DROP TABLE [FileNames];
CREATE TABLE [dbo].[FileNames]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](200) NULL
) ON [PRIMARY]
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = '[MultipleXLtoSQL_stage]')
DROP TABLE MultipleXLtoSQL_stage;
CREATE TABLE [dbo].[MultipleXLtoSQL_stage]
(
[Sno] [float] NULL,
[EmpID] [float] NULL,
[EmpName] [nvarchar](255) NULL,
[Checkin] [datetime] NULL,
[Checkout] [datetime] NULL,
[Working hours] [float] NULL,
[Status] [nvarchar](255) NULL
) ON [PRIMARY]
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = '[MultipleXLtoSQL]')
DROP TABLE MultipleXLtoSQL;
CREATE TABLE [dbo].[MultipleXLtoSQL]
(
[Sno] [float] NULL,
[EmpID] [float] NULL,
[EmpName] [nvarchar](255) NULL,
[Checkin] [datetime] NULL,
[Checkout] [datetime] NULL,
[Working hours] [float] NULL,
[Status] [nvarchar](255) NULL,
[File_name] [varchar](50) NULL,
[date] [date] NULL
) ON [PRIMARY]
/* —————————————————————–
2a. Create a stored procedure for getting the file count
—————————————————————–*/
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[usp_ImportMultipleFiles]’)
AND type IN (N’P’, N’PC’))
DROP PROCEDURE [dbo].[usp_ImportMultipleFiles]
CREATE PROCEDURE [dbo].[usp_ImportMultipleFiles]
#filepath varchar(500),
#pattern varchar(100),
#TableName varchar(128) = NULL
AS
SET QUOTED_IDENTIFIER OFF
DECLARE #query varchar(1000)
DECLARE #max1 int
DECLARE #count1 int
DECLARE #filename varchar(100)
SET #count1 = 0
DROP TABLE [FileNames]
CREATE TABLE #x (name varchar(200))
SET #query = ‘master.dbo.xp_cmdshell “dir ‘ + #filepath + #pattern + ‘ /b”‘
INSERT #x
EXEC (#query)
DELETE FROM #x
WHERE name IS NULL
SELECT
IDENTITY(int, 1, 1) AS ID,
name INTO [FileNames]
FROM #x
DROP TABLE #x
/*—————————————————————————-
2b. Create a stored procedure for inserting the excel files one by one
—————————————————————————-*/
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Article_InsertMultiplexlFile]')
AND type IN (N'P', N'PC'))
DROP PROCEDURE [Article_InsertMultiplexlFile];
CREATE PROCEDURE [dbo].[Article_InsertMultiplexlFile]
(#filepath varchar(max),
#table_name varchar(50) = NULL)
AS
BEGIN
DECLARE #v_filepath varchar(max),
#v_delete varchar(500),
#v_closebracket varchar(10),
#max1 int, #count1 int,
#filename varchar(100),
#v_message varchar(50),
#v_Date date,
#v_filename varchar(48),
#v_sheetname varchar(500);
SET #count1 = 0;
SET #v_closebracket = ')';
SET #v_sheetname = 'Sheet1'
EXEC usp_ImportMultipleFiles #filepath, '*.x*'
SET #max1 = (SELECT MAX(ID)
FROM [FileNames])
--print #max1
--print #count1
WHILE #count1 <= #max1
BEGIN
SET #count1 = #count1 + 1
SET #filename = NULL
SET #filename = (SELECT name
FROM [FileNames]
WHERE [id] = #count1)
IF #filename IS NOT NULL
BEGIN
BEGIN TRY
SET #v_filepath = 'INSERT INTO ' + #table_name + '
SELECT * FROM OPENROWSET(' + '''' + 'Microsoft.ACE.OLEDB.12.0' + '''' + ',' + '''' +
'Excel 12.0;Database=' + #filepath + #filename + '''' + ',' + '''' + 'SELECT * FROM [' + #v_sheetname + '$]''' + #v_closebracket
EXEC (#v_filepath)
End Try
BEGIN CATCH
SELECT
'ERROR WITH Filename #filename = ' + #filename + ' ' + ERROR_MESSAGE() AS Error_Description
END CATCH
End --End if
SET #v_date = CAST(SUBSTRING(#filename, 1, 10) AS date)
INSERT INTO MultipleXLtoSQL ([Date], [Sno], [EmpID], [EmpName], [Checkin], [Checkout], [Working hours], [Status], [File_name])
SELECT
#v_date,
[Sno],
[EmpID],
[EmpName],
[Checkin],
[Checkout],
[Working hours],
[Status],
#filename
FROM MultipleXLtoSQL_stage
Truncate table MultipleXLtoSQL_stage
End
--While
End
/*—————————————————————————-
Execute the Stored Procedure (Give the folder path)
—————————————————————————-*/
EXEC [dbo].[Article_InsertMultiplexlFile] 'D:\MultipleExcel2SQL\ArticleInputFiles\',
'MultipleXLtoSQL_stage'
/*—————————————————————————-
4a. To see how many records were imported and from which file (Query 1)
—————————————————————————-*/
SELECT
FILE_NAME,
COUNT(*) No_of_Records
FROM MultipleXLtoSQL
GROUP BY FILE_NAME;
/*—————————————————————————-
4b. To see all the records from table MultipleXLtoSQL (Query 2)
—————————————————————————-*/
SELECT
[Date],
[Sno],
[EmpID],
[EmpName],
[Working hours],
[Status],
[File_name]
FROM MultipleXLtoSQL;
/*—————————————————————————-
4c. To see total number of present and absent days (Query 3)
—————————————————————————-*/
SELECT
Empname,
COUNT(status) PRESENT_DAYS,
0 ABSENT_DAYS
FROM MultipleXLtoSQL
WHERE status = 'Present'
GROUP BY Empname UNION SELECT
Empname,
0,
COUNT(status) ABSENT_DAYS
FROM MultipleXLtoSQL
WHERE status = 'Absent'
GROUP BY Empname
/*—————————————————————————-
4d. To see the details of a selected employee (Query 4)
—————————————————————————-*/
SELECT
[Date],
[Sno],
[EmpID],
[EmpName],
[Working hours],
[Status],
[File_name]
FROM MultipleXLtoSQL
WHERE Empname = 'A'
/*—————————————————————————-
–To access the files in folders
—————————————————————————-*/
/*
SET ANSI_PADDING OFF
GO
EXEC sp_configure 'show advanced options',
1
reconfigure with override
GO
EXEC sp_configure 'xp_cmdshell',
1
reconfigure with override
GO
*/

I see two errors here:
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Must declare the scalar variable "#filepath".
Get a very simple script to work, and then build on that. Can you try it like this?
insert into test.dbo.Categories
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:\Users\Excel\Desktop\Book1.xls;
HDR=yes','Select * from [Sheet1$]')

Related

Executing TSQL batch multiple times through dynamic sql

I'm using SQL SERVER 2017 (Developper Edition 64 Bit) on a Windows 10 Machine. I'm trying to execute in a dynamic sql a batch multiples times through GO and it won't work.
But the sql Statement will work if it is not execute dynamically. The goal is to do it dynamically and I still don't figure out what I am doing wrong.
Here is how the definition tables look like:
ParentTable
(
Id uniqueidentifier DEFAULT (newsequentialid()) not null,
Created datetime not null,
Creator uniqueidentifier not null,
Modifier uniqueidentifier null,
Modified datetime null
)
ChildTable
(
Id uniqueidentifier DEFAULT (newsequentialid()) not null,
ParentTable_Id not null,
Created datetime not null,
Creator uniqueidentifier not null,
Modifier uniqueidentifier null,
Modified datetime null
)
This is what I've tried so far:
create Procedure InsertIntoChildTable
AS
BEGIN
DECLARE #countDset int
DECLARE #todaysdate datetime
DECLARE #UserName uniqueidentifier
DECLARE #ParentTable_Id uniqueidentifier
DECLARE #insertIntoChildTable nvarchar(max)
DECLARE #ChildTableName nvarchar(35)
SET #ChildTableName = ChildTable
SET #countDset = 6
SET #todaysdate = GETDATE()
SET #UserName = 'e86aacf4-9887-e911-9724-4439c492b2a7'
BEGIN TRY
BEGIN TRANSACTION
SET #insertIntoChildTable = 'INSERT INTO ' + #ChildTableName + '
(ParentTable_Id, Created, Creator, Modified, Modifier)
VALUES ( (select max(Id) from ParentTable) , #todaysdate, #UserName ,
NULL, NULL) ' + ' GO ' + #countDset
EXECUTE sp_executesql #insertIntoChildTable,N'#ChildTableName
nvarchar(35), #todaysdate datetime, #UserName uniqueidentifier,
#countDset int', #ChildTableName = #ChildTableName, #todaysdate =
#todaysdate, #UserName = #UserName, #countDset = #countDset
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT 'Could not insert in the Child table'
ROLLBACK TRANSACTION
RETURN
END CATCH
END
After the Line with 'Go ' + #countDset it will automatically go into the Catch block and return.
Thank you
INSERT INTO ChildTable ( ParentTable_Id, Created, Creator, Modified, Modifier )
SELECT (select max(Id) from ParentTable) as ParentId , #todaysdate, #UserName ,
NULL, NULL
FROM
(
SELECT TOP #countDset '' As Dummy
FROM sys.Objects As A
CROSS JOIN sys.Objects As B
) As Multiplier
Guided through the example Zohar posted I could insert new Rows in the ChildTable using CROSS JOIN

SQL Server create database dynamically and use the database in the script

I have a script that can be represented by the following:
DECLARE #DatabaseNamePart VARCHAR(50) = 'Part1'
DECLARE #DataBaseName VARCHAR(70) = 'MyDataBase_' + #DatabaseNamePart
IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE [name] = #DataBaseName) BEGIN
DECLARE #SqlQuery NVARCHAR(150) = 'CREATE DATABASE ' + #DataBaseName
EXECUTE (#SqlQuery)
END
DECLARE #UseDatabase NVARCHAR(150) = 'USE ' + #DataBaseName
EXECUTE ( #UseDatabase )
/**************************************************************************/
/* CREATE TABLES */
/**************************************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE [name]='MyTable' AND xtype='U') BEGIN
CREATE TABLE MyTable (
[id] INT PRIMARY KEY NOT NULL IDENTITY,
[Name] VARCHAR(150) NOT NULL,
)
END
The problem is when I create the table after it's not created in the new database but in whatever database I am currently on.
Any idea on how to use a database that you just created and don't know the name in advance?
DECLARE #DatabaseNamePart VARCHAR(50) = 'Part1'
DECLARE #DataBaseName VARCHAR(70) = 'MyDataBase_' + #DatabaseNamePart
IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE [name] = #DataBaseName) BEGIN
DECLARE #SqlQuery NVARCHAR(150) = 'CREATE DATABASE ' + #DataBaseName
EXECUTE (#SqlQuery)
END
-- code edited - declaring a new variable and setting the dbname
Declare #newDBName VARCHAR(30)
SET #DBName = #DataBaseName
exec('USE '+ #DBName)
-- code edited
--Create tables query
IF NOT EXISTS (SELECT * FROM sysobjects WHERE [name]='MyTable' AND xtype='U') BEGIN
CREATE TABLE MyTable (
[id] INT PRIMARY KEY NOT NULL IDENTITY,
[Name] VARCHAR(150) NOT NULL,
)
END

SQL Server : USE instruction in stored procedure

I would like to execute this query in a stored procedure, but I get 2 errors :
a database of USE instruction not allowed in a procedure, function, or
a trigger.
Incorrect syntax near the keyword 'CREATE'. (Microsoft SQL
Server, Error: 154).
My code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_copytable_TEST]
#SourceServer nvarchar(255),
#SourceDatabase nvarchar(255),
#SourceSchema nvarchar(255),
#DestinationSchema nvarchar(255)
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX),
#id uniqueidentifier = NEWID()
BEGIN
IF NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'TablesLog_TEST')
CREATE TABLE [dbo].[TablesLog_TEST]
(
[id] [uniqueidentifier] NOT NULL,
[SourceServer] [nvarchar](255) NULL,
[SourceDatabase] [nvarchar](255) NULL,
[SourceSchema] [nvarchar](255) NULL,
[source] [nvarchar](max) NULL,
[destination] [nvarchar](255) NULL,
[timestamp] [datetime] NULL,
[message] [nvarchar](max) NULL,
[type] [smallint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT INTO dbo.TablesLog_TEST
SELECT
#id, #SourceServer, #SourceDatabase, #SourceSchema,
'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP,
'Start Copy', 1
BEGIN TRY
INSERT INTO dbo.TablesLog_TEST
SELECT
#id, #SourceServer, #SourceDatabase, #SourceSchema,
'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP,
'try 1', 1
-- Create destination schema if it doesn't exist
SELECT #SQL = N'IF NOT EXISTS (SELECT * FROM [' + #SourceDatabase + '].SYS.SCHEMAS WHERE NAME = [' + #DestinationSchema + '])
BEGIN
SELECT #SQL = N'USE ['+ #SourceDatabase +'];
EXEC(''CREATE SCHEMA '+ #DestinationSchema +' '')'
EXEC sp_executesql #SQL
END'
EXEC sp_executesql #SQL
END TRY
BEGIN CATCH
INSERT INTO dbo.TablesLog_TEST
SELECT #id, #SourceServer, #SourceDatabase, #SourceSchema,
'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP,
'ERROR: ' + ERROR_MESSAGE(), 0
END CATCH
--Return value:
SELECT 1;
END
Someone can help me please?
Best regards
Slim
Slim
This code will work
SELECT #SQL = N'IF NOT EXISTS (SELECT * FROM [' + #SourceDatabase + '].SYS.SCHEMAS WHERE NAME = ''' + #DestinationSchema + ''')
BEGIN
DECLARE #SQL NVARCHAR(MAX);
SELECT #SQL = N''USE ['+ #SourceDatabase +'];
EXEC(''''CREATE SCHEMA '+ #DestinationSchema +' '''')''
EXEC sp_executesql #SQL
END'
EXEC sp_executesql #SQL
As Sandip spotted you need to declare the #SQL variable in your dynamic code. When you use sp_executesql to run the dynamic code, it is effectively running in isolation to your main stored proc, and thus knows nothing about any variables declared previously. You'll see I've added a few more single quotes to get everything working; also replaced the [] in the SELECT statement so that #DestinationSchema appears as text, and not a column name.
As an aside, do you know how to use the debug tools in SQL Server Management Studio? Type the following
EXEC usp_copytable_TEST 'SourceServer', 'SourceDatabase', 'SourceSchema', 'DestinationSchema'
on its own in a new query window. Instead of pressing F5 to execute, press ALT+F5, this will invoke a debug session and you can now step through the code line by line, watch variables and so on. You'll find this very helpful as you can see the values of your dynamic SQL strings.
Try This:
USE [CORE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[usp_copytable_TEST]
#SourceServer nvarchar(255),
#SourceDatabase nvarchar(255),
#SourceSchema nvarchar(255),
#DestinationSchema nvarchar(255)
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX),
#id uniqueidentifier = NEWID()
BEGIN
If NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TablesLog_TEST')
CREATE TABLE [dbo].[TablesLog_TEST](
[id] [uniqueidentifier] NOT NULL,
[SourceServer] [nvarchar](255) NULL,
[SourceDatabase] [nvarchar](255) NULL,
[SourceSchema] [nvarchar](255) NULL,
[source] [nvarchar](max) NULL,
[destination] [nvarchar](255) NULL,
[timestamp] [datetime] NULL,
[message] [nvarchar](max) NULL,
[type] [smallint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT INTO dbo.TablesLog_TEST SELECT #id, #SourceServer,#SourceDatabase, #SourceSchema, 'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP, 'Start Copy', 1
BEGIN TRY
INSERT INTO dbo.TablesLog_TEST SELECT #id, #SourceServer,#SourceDatabase, #SourceSchema, 'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP, 'try 1', 1
-- Create destination schema if it doesn't exist
SELECT #SQL = N'IF NOT EXISTS (SELECT * FROM [' + #SourceDatabase + '].SYS.SCHEMAS WHERE NAME = [' + #DestinationSchema + '])
BEGIN
SELECT #SQL = N''USE ['+ #SourceDatabase +'];
EXEC(''CREATE SCHEMA '+ #DestinationSchema +' '')''
EXEC sp_executesql #SQL
END'
EXEC sp_executesql #SQL
END TRY
BEGIN CATCH
INSERT INTO dbo.TablesLog_TEST SELECT #id, #SourceServer,#SourceDatabase, #SourceSchema, 'GetAllTables', #DestinationSchema, CURRENT_TIMESTAMP, 'ERROR: ' + ERROR_MESSAGE(), 0
END CATCH
--Return value:
SELECT 1;
END
END
You seem to be missing some quotation marks when building your dynamic SQL
Try this
SELECT #SQL = N'IF NOT EXISTS (SELECT * FROM [' + #SourceDatabase + '].SYS.SCHEMAS WHERE NAME = [' + #DestinationSchema + '])
BEGIN
SELECT #SQL = N''USE ['+ #SourceDatabase +'];
EXEC(''CREATE SCHEMA '+ #DestinationSchema +' '')''
EXEC sp_executesql #SQL
END'
Thank you #Sandip Patel for your help,
Thank you Paul Bambury for your help
It work!!!
The problem was missing quotation marks when building my dynamic SQL.
Like this:
--Create Temporary table
SELECT #SQL ='SELECT * INTO SANDBOX.dbo.TempTables FROM OPENQUERY(['+#SourceServer+'],
''
SELECT * FROM ICTNONID.information_schema.tables where TABLE_SCHEMA = '''''+#SourceSchema+'''''
'')
WHERE TABLE_NAME NOT in (SELECT IGNORENAME FROM CORE.dbo.CopyTablesProdIgnore where IGNORETYPE = ''TABLE'' AND schemaname = '''+#SourceSchema+''')
'
EXEC sp_executesql #SQL

Parameter in dynamical sql server query

i have problem with passing parameters in my dynamical query. Here is the error message
Msg 50000, Level 11, State 1, Procedure WriteJobLog, Line 101 Error
writing job log: Line #90: [ERR] #7: Must declare the scalar variable
"#LastId".
and my sql code is:
ALTER PROCEDURE [WarehouseMgmt].[SyncReportServerFormatEntries]
#SyncJobId varchar(50),
#SyncJobStep varchar(50)=NULL, -- Sproc name will be used as a job step if not specified
#SyncExecId int=NULL, -- Will be obtained from #SyncJobStep step execution if not specified
#LastId BIGINT=NULL, -- Last transaction id to snyc, will be obtained from WarehouseMgmt.SyncSQLData if not specified
#SyncObjectName VARCHAR(50) = 'WarehouseMgmt.FactReportServerExecutionLog'
AS
..........
DECLARE #sql nvarchar(max);
DECLARE #server nvarchar(255) = (SELECT [Value] FROM [WarehouseMgmt].[SyncConfig] WHERE [Key] = 'ReportServerLinkedServer')
DECLARE #database nvarchar(255) = (SELECT [Value] FROM [WarehouseMgmt].[SyncConfig] WHERE [Key] = 'ReportServerDatabase')
SET #sql='MERGE [WarehouseMgmt].[DimReportServerFormatEntries] AS Target
USING(
SELECT CASE [Format]
WHEN ''RPL'' THEN ''View''
ELSE ''Export''
END [Name],
[Format] [OriginalFormatName],
LogEntryId
FROM OPENQUERY('+#server+',
''SELECT CASE [Format]
WHEN ''''RPL'''' THEN ''''View''''
ELSE ''''Export''''
END [Name],
[Format] [OriginalFormatName],
LogEntryId
FROM '+#database+'.dbo.[ExecutionLogStorage] WHERE LogEntryId > #LastId AND [Parameters] IS NOT NULL '' )
) AS Source
ON Source.LogEntryId=Target.SourceOrigId
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
[Name],
[OriginalFormatName],
[SourceOrigId],
SyncExecId
)
VALUES
(
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId],
#SyncExecId
)
OUTPUT
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId]
INTO #NewReportServerFormatEntries;'
EXEC sp_executesql #sql,N'#LastId bigint,#SyncExecId int',#LastId,#SyncExecId;
Not sure you'll get much benefit from passing parameters into dynamic SQL. Maybe try without the params?
ALTER PROCEDURE [WarehouseMgmt].[SyncReportServerFormatEntries]
#SyncJobId varchar(50),
#SyncJobStep varchar(50)=NULL, -- Sproc name will be used as a job step if not specified
#SyncExecId int=NULL, -- Will be obtained from #SyncJobStep step execution if not specified
#LastId BIGINT=NULL, -- Last transaction id to snyc, will be obtained from WarehouseMgmt.SyncSQLData if not specified
#SyncObjectName VARCHAR(50) = 'WarehouseMgmt.FactReportServerExecutionLog'
AS
..........
DECLARE #sql nvarchar(max);
DECLARE #server nvarchar(255) = (SELECT [Value] FROM [WarehouseMgmt].[SyncConfig] WHERE [Key] = 'ReportServerLinkedServer')
DECLARE #database nvarchar(255) = (SELECT [Value] FROM [WarehouseMgmt].[SyncConfig] WHERE [Key] = 'ReportServerDatabase')
SET #sql='MERGE [WarehouseMgmt].[DimReportServerFormatEntries] AS Target
USING(
SELECT CASE [Format]
WHEN ''RPL'' THEN ''View''
ELSE ''Export''
END [Name],
[Format] AS [OriginalFormatName],
LogEntryId
FROM OPENQUERY('+#server+',
''SELECT CASE [Format]
WHEN ''''RPL'''' THEN ''''View''''
ELSE ''''Export''''
END [Name],
[Format],
LogEntryId
FROM '+#database+'.dbo.[ExecutionLogStorage] WHERE LogEntryId > ' + ISNULL(CAST(#LastId AS NVARCHAR(MAX)), 'NULL') + ' AND [Parameters] IS NOT NULL '' )
) AS Source
ON Source.LogEntryId=Target.SourceOrigId
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
[Name],
[OriginalFormatName],
[SourceOrigId],
SyncExecId
)
VALUES
(
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId],
' + ISNULL(CAST(#SyncExecId AS NVARCHAR(MAX)), 'NULL') + '
)
OUTPUT
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId]
INTO #NewReportServerFormatEntries;'
EXEC sp_executesql #sql;
Since #LastId and #SyncExecId already come as parameters into this stored procedure, why don't you built the SQL statement concatenating the actual values ? Try this below. Note the direct concatenation of those parameters in the convert(varchar(250) phrase, where the reference to the parameters was present in your code earlier.
SET #sql='MERGE [WarehouseMgmt].[DimReportServerFormatEntries] AS Target
USING(
SELECT CASE [Format]
WHEN ''RPL'' THEN ''View''
ELSE ''Export''
END [Name],
[Format] [OriginalFormatName],
LogEntryId
FROM OPENQUERY('+#server+',
''SELECT CASE [Format]
WHEN ''''RPL'''' THEN ''''View''''
ELSE ''''Export''''
END [Name],
[Format] [OriginalFormatName],
LogEntryId
FROM '+#database+'.dbo.[ExecutionLogStorage] WHERE LogEntryId > ' + convert(varchar(250), #LastId) + ' AND [Parameters] IS NOT NULL '' )
) AS Source
ON Source.LogEntryId=Target.SourceOrigId
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
[Name],
[OriginalFormatName],
[SourceOrigId], ' + convert(varchar(250), #SyncExecId) + '
)
VALUES
(
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId], ' + convert(varchar(250), #SyncExecId) + '
)
OUTPUT
ISNULL(Source.[Name],''<UNKNOWN>''),
ISNULL(Source.[OriginalFormatName],''<UNKNOWN>''),
Source.[LogEntryId]
INTO #NewReportServerFormatEntries;'

how Do I list all table names in SQL Server using T-SQL?

SELECT name FROM sys.databases -- this can list all database name in the server
user database
SELECT * FROM INFORMATION_SCHEMA.TABLES
-- these two line can list the table for one particular database
But how can I output the results like below?
Database Table
--------- -------------
db1 t1
db1 t2
db2 t1
... ...
sp_msforeachdb 'select "?" AS db, * from [?].sys.tables'
Here is a stored procedure I use constantly to list all my tables ordered by the space used by them in the database.
GO
/****** Object: StoredProcedure [dbo].[dba_SpaceUsed] Script Date: 03/16/2010 15:09:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[dba_SpaceUsed]
#SourceDB varchar ( 128 ) = null -- Optional database name
-- If omitted, the current database is reported.
, #SortBy char(1) = 'S' -- N for name, S for Size
-- T for table name
AS
SET NOCOUNT ON
DECLARE #sql nvarchar (4000)
IF #SourceDB IS NULL BEGIN
SET #SourceDB = DB_NAME () -- The current DB
END
--------------------------------------------------------
-- Create and fill a list of the tables in the database.
CREATE TABLE #Tables ( [schema] sysname
, TabName sysname )
SELECT #sql = 'insert #tables ([schema], [TabName])
select TABLE_SCHEMA, TABLE_NAME
from ['+ #SourceDB +'].INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = ''BASE TABLE'''
EXEC (#sql)
---------------------------------------------------------------
-- #TabSpaceTxt Holds the results of sp_spaceused.
-- It Doesn't have Schema Info!
CREATE TABLE #TabSpaceTxt (
TabName sysname
, [Rows] varchar (11)
, Reserved varchar (18)
, Data varchar (18)
, Index_Size varchar ( 18 )
, Unused varchar ( 18 )
)
---------------------------------------------------------------
-- The result table, with numeric results and Schema name.
CREATE TABLE #TabSpace ( [Schema] sysname
, TabName sysname
, [Rows] bigint
, ReservedMB numeric(18,3)
, DataMB numeric(18,3)
, Index_SizeMB numeric(18,3)
, UnusedMB numeric(18,3)
)
DECLARE #Tab sysname -- table name
, #Sch sysname -- owner,schema
DECLARE TableCursor CURSOR FOR
SELECT [SCHEMA], TabNAME
FROM #tables
OPEN TableCursor;
FETCH TableCursor into #Sch, #Tab;
WHILE ##FETCH_STATUS = 0 BEGIN
SELECT #sql = 'exec [' + #SourceDB
+ ']..sp_executesql N''insert #TabSpaceTxt exec sp_spaceused '
+ '''''[' + #Sch + '].[' + #Tab + ']' + '''''''';
Delete from #TabSpaceTxt; -- Stores 1 result at a time
EXEC (#sql);
INSERT INTO #TabSpace
SELECT #Sch
, [TabName]
, convert(bigint, rows)
, convert(numeric(18,3), convert(numeric(18,3),
left(reserved, len(reserved)-3)) / 1024.0)
ReservedMB
, convert(numeric(18,3), convert(numeric(18,3),
left(data, len(data)-3)) / 1024.0) DataMB
, convert(numeric(18,3), convert(numeric(18,3),
left(index_size, len(index_size)-3)) / 1024.0)
Index_SizeMB
, convert(numeric(18,3), convert(numeric(18,3),
left(unused, len([Unused])-3)) / 1024.0)
[UnusedMB]
FROM #TabSpaceTxt;
FETCH TableCursor into #Sch, #Tab;
END;
CLOSE TableCursor;
DEALLOCATE TableCursor;
-----------------------------------------------------
-- Caller specifies sort, Default is size
IF #SortBy = 'N' -- Use Schema then Table Name
SELECT * FROM #TabSpace
ORDER BY [Schema] asc, [TabName] asc
ELSE IF #SortBy = 'T' -- Table name, then schema
SELECT * FROM #TabSpace
ORDER BY [TabName] asc, [Schema] asc
ELSE -- S, NULL, or whatever get's the default
SELECT * FROM #TabSpace
ORDER BY ReservedMB desc
;
DROP TABLE #Tables
DROP TABLE #TabSpaceTxt
DROP TABLE #TabSpace
--Thanks to Andrew Novick
if you need one result set, try this:
DECLARE #AllTables table (DatabaseName sysname, TableName sysname)
DECLARE #Current sysname
,#SQL1 varchar(500)
,#SQL2 varchar(500)
,#SQL3 varchar(500)
,#SQL varchar(1500)
SELECT TOP 1 #Current=Name FROM sys.databases Order By Name
SET #SQL1='select db.name, t.TABLE_NAME from '
SET #SQL2='.sys.databases db inner join '
SET #SQL3='.INFORMATION_SCHEMA.TABLES t on db.name = t.TABLE_CATALOG'
WHILE #Current IS NOT NULL
BEGIN
SET #SQL=#SQL1+#Current+#SQL2+#Current+#SQL3
INSERT INTO #AllTables
EXEC (#SQL)
SELECT TOP 1 #Current=Name FROM sys.databases WHERE Name>#Current Order By Name
IF ##ROWCOUNT=0 BREAK
END
SELECT * FROM #AllTables ORDER BY DatabaseName,TableName
If you're lucky enough to still be using sql2000:
CREATE TABLE #AllTables (DatabaseName sysname, TableName sysname)
DECLARE #Current sysname
,#SQL1 varchar(500)
,#SQL2 varchar(500)
,#SQL3 varchar(500)
,#SQL varchar(1500)
SELECT TOP 1 #Current=Name FROM sysdatabases Order By Name
SET #SQL1='select db.name, t.TABLE_NAME from '
SET #SQL2='sysdatabases db inner join '
SET #SQL3='.INFORMATION_SCHEMA.TABLES t on db.name = t.TABLE_CATALOG'
WHILE #Current IS NOT NULL
BEGIN
SET #SQL=#SQL1+#SQL2+#Current+#SQL3
--PRINT #SQL
SET NOCOUNT ON
INSERT INTO #AllTables
EXEC (#SQL)
SET NOCOUNT OFF
SELECT TOP 1 #Current=Name FROM sysdatabases WHERE Name>#Current Order By Name
IF ##ROWCOUNT=0 BREAK
END
SELECT * FROM #AllTables
--where TableName = 'at_errorlog'
ORDER BY DatabaseName,TableName
DROP TABLE #AllTables
select table_name from user_tables;

Resources