Error in Creating stored procedure - sql-server

Anybody tell me what's wrong with creating this stored procedure.
CREATE PROC ImportData
AS
BEGIN
DECLARE #DatabasePath VARCHAR(MAX)
SET #DatabasePath = 'E:\ABC.xls'
DECLARE #sql nvarchar(MAX)
SET #sql = '
INSERT INTO [dbo].[Table_1]
SELECT *
FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',
''Excel 8.0;Database=' + #DatabasePath + ',
''SELECT * FROM [Sheet1$]'') AS xlsTable'
EXEC sp_executesql #sql
GO
END
ERROR:-
Incorrect syntax near '#sql'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.

Remove the GO from within the Stored Procedure
Something like
CREATE PROC ImportData
AS
BEGIN
DECLARE #DatabasePath VARCHAR(MAX)
SET #DatabasePath = 'E:\ABC.xls'
DECLARE #sql nvarchar(MAX)
SET #sql = '
INSERT INTO [dbo].[Table_1]
SELECT *
FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',
''Excel 8.0;Database=' + #DatabasePath + ',
''SELECT * FROM [Sheet1$]'') AS xlsTable'
EXEC sp_executesql #sql
END

You cannot have a batch terminator (GO) in the body of a stored procedure.

Related

Invalid column name when using dynamic SQL

I want to execute the following T-SQL dynamic statement:
CREATE PROCEDURE MergeTable #TableName NVARCHAR(max)
AS BEGIN
DECLARE #MergeStatement NVARCHAR(max)
SET #MergeStatement = 'SELECT Query FROM dbo.QueryMergeDWH WHERE SourceTableName = ' + #TableName
EXEC sp_executesql #MergeStatement
END
EXEC MergeTable #TableName = 'SGPREINVOICE'
However, this gives me the following error:
Msg 207, Level 16, State 1, Line 17 Invalid column name
'SGPREINVOICE'.
This actually works:
SELECT 'SELECT Query FROM dbo.QueryMergeDWH WHERE SourceTableName = ' + 'SGPREINVOICE'
What am I doing wrong here?
You need to parameterize you dynamic query. So you pass #TableName all the way through
CREATE PROCEDURE MergeTable #TableName NVARCHAR(max)
AS
DECLARE #MergeStatement NVARCHAR(max);
SET #MergeStatement = '
SELECT Query
FROM dbo.QueryMergeDWH
WHERE SourceTableName = #TableName;
';
EXEC sp_executesql
#MergeStatement,
N'#TableName nvarchar(max)',
#TableName = #TableName;
GO
But it's unclear what's dynamic about that, you could just as well do
CREATE PROCEDURE MergeTable #TableName NVARCHAR(max)
AS
SELECT Query
FROM dbo.QueryMergeDWH
WHERE SourceTableName = #TableName;
GO

Pass table name and date as parameters to stored procedure to delete rows with where clause

create PROC usp_delete_qu (
#table NVARCHAR(128),
#new_date datetime) AS BEGIN
DECLARE #sql NVARCHAR(MAX);
-- construct SQL
SET #sql = N'delete FROM ' + #table + N' where modified_date < ' +#new_date
-- execute the SQL
EXEC sp_executesql #sql;
END;
I create a stored procedure which I need to delete rows with modified date. But while I tried to execute this I got error:
Msg 241, Level 16, State 1, Procedure usp_query, Line 10 [Batch Start Line 19]
Conversion failed when converting date and/or time from character string.
My intention is to use this stored procedure to delete rows in all tables in my database.
Just use a parameter in your dynamic statement:
CREATE PROCEDURE usp_delete_qu
#table NVARCHAR(128),
#new_date datetime
AS BEGIN
DECLARE #sql NVARCHAR(MAX);
DECLARE #rc int
-- construct SQL
SET #sql = N'delete FROM ' + QUOTENAME(#table) + N' where modified_date < #new_date'
-- execute the SQL
EXEC #rc = sp_executesql #sql, N'#new_date datetime', #new_date
IF #rc <> 0 PRINT 'Error'
END
You'll have to convert your date into string when using dynamic query.
create PROC usp_delete_qu (
#table NVARCHAR(128),
#new_date datetime) AS BEGIN
DECLARE #sql NVARCHAR(MAX);
-- construct SQL
SET #sql = N'delete FROM ' + #table + N' where modified_date < ''' + CONVERT(NVARCHAR(50), #new_date) + ''' '
-- execute the SQL
EXEC sp_executesql #sql;
END;

Amount of single quotes when running dynamic SQL with variable

I am having a real hard time sorting out the number of ' I should have within the following SQL statement:
declare #sql varchar(max)
declare #LetterID varchar(max) = 'c01as1'
set #sql =
'SELECT fltr.tency_seq_no FROM OPENQUERY(loopback,
''SET FMTONLY OFF; EXEC BST.[LET].[LETTERBUILD] #LetterCode =
''''\\SVR-QL4APPLIVE\QLSHAREPOINT\LETTERS\DATAFILES\
'''+#LetterID+'''
.csv''''
WITH RESULT SETS (tency_seq_no VARCHAR(255))''
) AS fltr'
exec (#sql)
Current error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'c01as1'
Just to clarify, the error is referring to the #LetterID variable within the dynamic SQL , not when declaring the parameter
Print of # SQL
SELECT fltr.tency_seq_no
FROM OPENQUERY(loopback, 'SET FMTONLY OFF; EXEC BST.[LET].[LETTERBUILD] #LetterCode = ''\\SVR-QL4APPLIVE\QLSHAREPOINT\LETTERS\DATAFILES\'c01as1'.csv''
WITH RESULT SETS (tency_seq_no VARCHAR(255));'
) AS fltr
Any help would be appreciated!
I think the error has got something to do with unwanted line breaks etc in the original code. Try this instead:
DECLARE #sql VARCHAR(MAX);
DECLARE #LetterID VARCHAR(MAX) = 'c01as1';
SET #sql = 'SELECT fltr.tency_seq_no FROM OPENQUERY(loopback,
''SET FMTONLY OFF; EXEC BST.[LET].[LETTERBUILD] #LetterCode = ''''\\SVR-QL4APPLIVE\QLSHAREPOINT\LETTERS\DATAFILES\'
+ #LetterID + '.csv''''
WITH RESULT SETS (tency_seq_no VARCHAR(255))''
) AS fltr';
EXEC (#sql);
When I ran into this difficulty a few months ago, I created a function that would perform a double-up on the quotes for dynamic SQL. Instead of searching the string manually each time for quotes needing to be doubled, this scalar function can perform this task. This can prevent potentially cluttering up the script when future modifications are performed, such as adding additional variables, as well as improving readability.
Function as follows:
CREATE FUNCTION dbo.fn_duplicateQuotes
(#string varchar(max),
#level int)
RETURNS varchar(max)
AS
BEGIN
/*Doubles-up quotation marks for nested dynamic SQL
level can be set greater than 1 to add additional doubled-up quotes
for further nested dynamic SQL*/
/*Double up quotes*/
set #string = REPLACE(#string, '''', REPLICATE('''', (#level) * 2))
/*Return Value*/
return #string
END
Dynamic SQL as follows:
declare #SQL nvarchar(max)
declare #LetterID varchar(max) = 'c01as1'
set #SQL = 'SET FMTONLY OFF; EXEC BST.[LET].[LETTERBUILD] #LetterCode =
''\\SVR-QL4APPLIVE\QLSHAREPOINT\LETTERS\DATAFILES\' + #LetterID + '.csv''
WITH RESULT SETS (tency_seq_no VARCHAR(255));'
set #SQL = 'SELECT fltr.tency_seq_no FROM OPENQUERY(loopback,
''' + dbo.fn_duplicateQuotes(#SQL, 1) + '''
) AS fltr'
print #SQL
exec (#SQL)
Print of #SQL returns:
SELECT fltr.tency_seq_no FROM OPENQUERY(loopback,
'SET FMTONLY OFF; EXEC BST.[LET].[LETTERBUILD] #LetterCode =
''\\SVR-QL4APPLIVE\QLSHAREPOINT\LETTERS\DATAFILES\c01as1.csv''
WITH RESULT SETS (tency_seq_no VARCHAR(255));'
) AS fltr

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'D:'

I trying to call a stored procedure:
CREATE PROCEDURE [dbo].[uspImportDepartment2]
#filePath nvarchar(255),
#formatPath varchar(255),
#countInsert Int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sqlstmt nvarchar(255)
DECLARE #results table (result xml)
--Build the Dynamic SQL Statement to get the data from the xml file
SET #sqlstmt= N'SELECT * FROM OPENROWSET ( BULK ' + #filePath + ', FORMATFILE=''' + #formatPath + ''', FIRSTROW=1, MAXERRORS=0)AS xmlData'
-- Insert the results of the dynamic SQL Statement into the temporary table variable.
INSERT INTO #results EXEC (#sqlstmt)
select #countInsert = count(*) from #results
--DECLARE #xmlDoc XML
--SELECT #xmlDoc = result FROM #results
END
GO
And execution code:
DECLARE #count1 int
EXEC [dbo].[uspImportDepartment2] #filePath = 'D:\test_1.txt',
#formatPath = 'D:\test_1_c.fmt', #countInsert = #count1 OUTPUT
SELECT #count1 as AAAA
But it throws an error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'D:'.
Can somebody tell me what the problem is?
Thanks!
Quotes are missing , write as:
SET #sqlstmt= N'SELECT xmlData.* FROM OPENROWSET
(BULK ''' + #filePath +''',
FORMATFILE=''' + #formatPath + ''',
FIRSTROW=1, MAXERRORS=0
)AS xmlData'
You can learn more about the syntax of OPENROWSET function from here:
http://msdn.microsoft.com/en-IN/library/ms190312(v=sql.100).aspx
I had the same issue. I think that you need a space before "AS"
SET #sqlstmt= N'SELECT * FROM OPENROWSET ( BULK ' + #filePath + ', FORMATFILE=''' + #formatPath + ''', FIRSTROW=1, MAXERRORS=0) AS xmlData'

declare variable in a table in SQL

I have a below query that requires help
Declare #DB varchar(3)
set #DB = 'C01'
SELECT * FROM SVBNORD+#DB WHERE ORDER_DATE = ''
But I get a message
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '+'.
Can you please help me correct my statement.
You should use execute to dynamically call the query:
Declare #DB varchar(3)
set #DB = 'C01'
execute ('SELECT * FROM SVBNORD'+#DB+' WHERE ORDER_DATE = '''' ')
You can't do this in normal sql. You can however build up sql dynamically and execute it, like so:
DECLARE #sql NVARCHAR(MAX);
SET #sql =
'SELECT * FROM SVBNORD' + #DB + N'WHERE ORDER_DATE = ''''';
EXEC(#sql);
You'll need to double up any single quotes in the query.

Resources