Must declare scalar variable error when executing t-sql script - sql-server

I am trying to execute the below script to get the mdf and ldf file details from a .back file. It throws an error
Incorrect syntax at H.
Declare #backupPath NVARCHAR(300);
set #backupPath =N'H:\path\of\backupfile.bak';
declare #qry NVARCHAR(max) = N'RESTORE FILELISTONLY from disk = ';
set #qry = #qry + #backupPath ;
exec(#qry)
When I tried with the below line
set #qry = 'Restore filelistonly from #backuppath'
it would throw the error "declare scalar variable #qry.
Please help.

If you print #qry you will see that syntax is wrong, the quotes are missing.
Try this:
Declare #backupPath NVARCHAR(300);
set #backupPath =N'''H:\path\of\backupfile.bak''';
declare #qry NVARCHAR(max) = N'RESTORE FILELISTONLY from disk = ';
set #qry = #qry + #backupPath ;
exec(#qry)

Related

Passing a file path as a variable in SQL Server

I'm trying to add a file to a file group in order to create a partition in SQL Server. When I pass in a hardcoded file path to the the filename, the code works. But when I use a variable for the file path, I get an error
Incorrect syntax near #FilePath or Unexpected symbol #FilePath
This is my code:
USE StudentRepository
BEGIN
SET NOCOUNT ON;
DECLARE #FilePath NVARCHAR(MAX) = "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\",
#FileName NVARCHAR(MAX) = "FirstTerm2020",
#FileExt NVARCHAR(MAX) = ".NDF";
DECLARE #count INT = 0;
ALTER DATABASE StudentRepository
ADD FILE
(
NAME = 'FirstTerm2020',
FILENAME = #FilePath + #FileName + #FileExt, --Error here!
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP FirstTerm2020
END
When I pass a hardcoded file path to the filename, it works and creates the required partitions. as below
--Code omitted for brevity
FILENAME = "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\FirstTerm2020.NDF" --No error!
Please I need some help. How do I pass a file path as a variable?
This is how I solved the problem. I create a dynamic sql and passed the filepath variable like this.
USE StudentRepository
BEGIN
SET NOCOUNT ON;
DECLARE #FilePath NVARCHAR(MAX) = 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\',
#FileName NVARCHAR(MAX) = 'SecondTerm2022',
#FileExt NVARCHAR(MAX) = '.NDF';
DECLARE #count INT = 0;
DECLARE #sql NVARCHAR(MAX) = '
ALTER DATABASE StudentRepository ADD FILEGROUP ' + #FileName + ';
ALTER DATABASE StudentRepository
ADD FILE
(
NAME = '+ #FileName + ',
FILENAME = ''' + #FilePath + #FileName + #FileExt + ''',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP '+ #FileName
END
EXEC sp_executesql #sql
My major problem was that I was ommitting the three single quotes near #FilePath

Error "Incorrect syntax near '#part1' sql server

I am trying to make a dynamic stored procedure.
Here is the initial code
Declare #sqlstrsel as nvarchar(max) ;
Declare #cols as nvarchar(max) ;
Declare #tables as nvarchar(max) ;
Declare #condt as nvarchar(max) ;
Set #cols='*'
Set #tables='products'
Set #condt=''
Set #sqlstrsel = 'select ' + #cols+ 'from ' +#table +#condt
Exec (#sqlstrsel)
This code works fine, but when changed to a stored procedure like below
Alter proc selectT
#cols nvarchar(max) ;
#tables nvarchar(max) ;
#condt nvarchar(max) ;
As
Begin
Declare #sqlstrsel as nvarchar(max) ;
Set #sqlstrsel = 'select ' + #cols+ 'from ' +#table +#condt
Exec (#sqlstrsel);
End
When I execute this proc in a new query, by providing the parameters,
Set #par1='*'
Set #par2= 'products'
Set #par3 =''
Exec selectT(#par1,#par2,#par3)
I get two errors
Procedure or function 'selectt' expect parameter '#cols which was not provided,
And
Incorrect syntax near' #par1'
Par1 to the par 3 are declared beforehand.

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

Incorrect syntax near 'c:'

this a sample of test SP i was created befor
when i run it "Incorrect syntax near 'c:'."
create PROCEDURE [dbo].[TextImpotedSP2]
AS
set #path = 'c:temp\TextImpoted0.txt'
SET NOCOUNT ON;
DECLARE #bulk_cmd NVARCHAR(max);
SET #bulk_cmd =
'BULK
INSERT TextImpoted FROM '+ #path1 + '; WITH (FIELDTERMINATOR = ' + ';' ',ROWTERMINATOR = ' + '\n'+ ' )';
EXEC sp_executesql #bulk_cmd
--*************************
any one have any idea?
There seem to be several issues. First, the variable path is never declared, and it's also incorrectly referred to as path1 which needs to be changed. Second, some of the values in the bulk_cmd string needs to be quoted.
A corrected version that should work:
CREATE PROCEDURE [dbo].[TextImpotedSP2]
AS
DECLARE #path NVARCHAR(max)
SET #path = 'c:\temp\TextImpoted0.txt'
SET NOCOUNT ON;
DECLARE #bulk_cmd NVARCHAR(max);
SET #bulk_cmd = '
BULK INSERT TextImpoted
FROM '''+ #path + '''
WITH
(
FIELDTERMINATOR = ' + ''';''' + ',
ROWTERMINATOR = ' + '''\n'''+ '
)';
--PRINT #bulk_cmd
EXEC sp_executesql #bulk_cmd
Also, the path string 'c:temp\TextImpoted0.txt' should probably be 'c:\temp\TextImpoted0.txt' as you might get unexpected results if you use a relative path.
Edit: added the solution to the follow-up question that were posted as an answer...
CREATE PROCEDURE [dbo].[TextImpoted01]
AS
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(100)
SELECT TOP (1) #SQL = total FROM DealCounter
DECLARE #path NVARCHAR(max)
SET #path = 'c:\temp\TextImpoted'+ #SQL + '.txt'
DECLARE #bulk_cmd NVARCHAR(max);
SET #bulk_cmd = '
BULK INSERT TextImpoted
FROM '''+ #path + '''
WITH
(
FIELDTERMINATOR = ' + ''';''' + ',
ROWTERMINATOR = ' + '''\n'''+ '
)';
--PRINT #bulk_cmd
EXEC sp_executesql #bulk_cmd
change
set #path = 'c:temp\TextImpoted0.txt'
to
set #path = 'c:\temp\TextImpoted0.txt'
the \ is important

SQL Server - Variable declared but still says "Must declare the scalar variable"

I'm trying to run this set of SQL commands on Microsoft SQL Server but I am getting this error:
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "#dbstatus".
I thought I did declare the variable so I'm not sure why it's still throwing the error?
DECLARE #dbname nvarchar(100)
DECLARE #dbstatus varchar(500)
DECLARE #sqlCommand NVARCHAR(1000)
create table #temptable (dbname nvarchar(100), status varchar(500))
DECLARE c1 CURSOR READ_ONLY
FOR
SELECT '[' + name + ']' FROM sys.databases WHERE name = 'EDDS1084543'
OPEN c1
FETCH NEXT FROM c1 INTO #dbname
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sqlCommand = 'SET #dbstatus = (SELECT Status FROM ' + #dbname + '.[EDDSDBO].[dtSearchIndex])'
EXECUTE sp_executesql #sqlCommand
INSERT INTO #tempTable(dbname, [status])VALUES (#dbname, #dbstatus)
FETCH NEXT FROM c1 INTO #dbname
END
CLOSE c1
DEALLOCATE c1
EXEC/sp_executesql creates a new connection (SPID) to the SQL Server, which is not your current session, so it cannot see the variable. Check the documentation.
Basically, you have to declare the parameter you want to pass into the call, and give it a value. In this case, both have to include the OUTPUT specifier.
EXECUTE sp_executesql #sqlCommand, '#dbstatus varchar(500) output', #dbstatus output
The problem is here:
SET #sqlCommand = 'SET #dbstatus = (SELECT Status FROM ' + #dbname + '.[EDDSDBO].[dtSearchIndex])'
EXECUTE sp_executesql #sqlCommand
This causes the server to execute the value of #sqlCommand as a standalone statement. Within this statement, #dbstatus has not been declared as a variable, hence the error. This is what's getting executed:
SET #dbstatus = (SELECT Status FROM [value in #dbname].[EDDSDBO].[dtSearchIndex])
Try this instead:
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sqlCommand = 'SET #dbstatus = (SELECT Status FROM ' + #dbname + '.[EDDSDBO].[dtSearchIndex])'
EXECUTE sp_executesql #sqlCommand, '#dbstatus varchar(500) output', #dbstatus output
INSERT INTO #tempTable(dbname, [status])VALUES (#dbname, #dbstatus)
FETCH NEXT FROM c1
INTO #dbname
END

Resources