SQL Server stored procedures calls require variable declaration (but already declared) - sql

I have a few stored procedures which I call in this order.
So, from the first stored procedure, importTaxonomy I call parseXBRL and from parseXBRL I call createTaxonomyStructure.
But in this flow, when the code of the last stored procedure is executed I get an error.
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "#temporaryTable".
Below you can find the first few lines code of this stored procedure:
CREATE PROCEDURE createTaxonomyStructure #taxonomy_table nvarchar(max), #debug bit = 0
AS
DECLARE #statement NVARCHAR(MAX)
DECLARE #temporaryTable TABLE (taxonomyLine NVARCHAR(MAX)) -- declared a temporary table to avoid creating a Dynamic Query with the entire cursor, but just with the temporary table
DECLARE #taxonomyLine NVARCHAR(MAX) -- variable that will store one line of the taxonomy
SET #statement = 'INSERT INTO #temporaryTable SELECT taxText FROM ' + #taxonomy_table -- statement that will import the taxonomy in the temporary table
EXEC sp_executesql #statement
DECLARE taxonomyCursor CURSOR READ_ONLY FAST_FORWARD FOR -- read each line in the taxonomy to parse afterwards
SELECT taxonomyLine
FROM #temporaryTable
OPEN taxonomyCursor
FETCH NEXT FROM taxonomyCursor INTO #taxonomyLine -- parsing each taxonomy line and extracting the values from important attributes
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #id_element NVARCHAR(MAX)
DECLARE #leaf_element NVARCHAR(MAX)
SELECT #id_element = (SELECT dbo.extract_IDElement(#taxonomyLine))
SELECT #leaf_element = (SELECT dbo.extract_IDLeafElement(#taxonomyLine))
SET #statement = 'UPDATE ' + #taxonomy_table + ' SET fullName = ''' + #id_element + ''', leafName = ''' + #leaf_element + '''';
EXEC sp_executesql #statement
END
I do declare this variable, but I still get the error and I don't understand why.
How can I get over this error?
Thanks!

the error is here:
SET #statement = 'INSERT INTO #temporaryTable SELECT taxText FROM ' + #taxonomy_table -- statement that will import the taxonomy in the temporary table
EXEC sp_executesql #statement
change it to
set #statement = 'select taxText from ' + #taxonomy_table
insert into #temporaryTable
exec sp_executesql #statement
The error is happening because in the scope of executing #statement there's no variable table #temporaryTable.

Related

Query with variable tablename

I don't know why I keep bumping into these, but I have a small problem with a stored procedure. The only special in it is the variable Tablename:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE dbo.ProdTijdCompare
#TABLENAME SYSNAME,
#scanner nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX);
SELECT #SQL = 'select SUM(tijd) from ' + #TABLENAME + 'where Scanner = #scanner'
EXEC sp_executesql #SQL;
END
GO
The error I'm getting when executing in SSMM:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
(1 row(s) affected)
You need a space between #TableName and where:
SELECT #SQL = 'select SUM(tijd) from ' + #TABLENAME + ' where Scanner = #scanner';
This type of error is incredibly obvious if you just print out the SQL before running it.
Always quote table names in dynamic SQL to avoid SQL Injection (cf QUOTENAME)
Second, supply the #scanner parameter to the sp_executesql procedure as you can see in the sample below:
SELECT #SQL = 'select SUM(tijd) from ' + QUOTENAME(#TABLENAME) + ' where Scanner = #scanner'
EXEC sp_executesql #SQL, N'#scanner NVARCHAR(50)', #scanner;

No output when stored procedure is executed

No output when stored procedure is executed. The select statement works when I create a new query , but does not return any values when calling the store procedure within my Web app.
You want a dynamic sql.
try this.
Declare #strSQL nvarchar(2000)
set #strSQL = 'SELECT * FROM investor WHERE ' + #search_by + ' = ''' + #col + ''''
execute sp_executesql #strSQL

Execute Stored Procedure from Stored Procedure w/ dynamic SQL capturing output

Inside a stored procedure (A) I need to call a stored procedure (X) inside a specific database and capture the output. X returns a single value.
From what I understand I need to provide the DB name of X to the stored procedure in A and I need to use dynamic SQL to build the query on execution targeting the desired database.
What am unable to figure out is how to capture output from X in A to work with the result.
You could use sp_executesql to dynamically call your nested Stored Procedure.
DECLARE #db AS SYSNAME
DECLARE #return_value AS INT
DECLARE #output_value AS INT
DECLARE #sql AS NVARCHAR(MAX)
-- Set your DB name
SET #db = N'mydb'
/*
Use sp_executesql to dynamically pass in the db and stored procedure
to execute while also defining the values and assigning to local variables.
*/
SET #sql = N'EXEC #rtn = ' + #db + '.dbo.[your_stored_procedure] #output OUTPUT'
EXEC sp_executesql #sql
, N'#rtn AS INT, #output AS INT OUTPUT'
, #return_value = #rtn
, #output_value = #output OUTPUT
Adding to the above answer, following is the way to call stored procedures dynamically by passing parameters.
DECLARE #SpName VARCHAR(1000)
SELECT #SpName = DeleteLiveSP FROM dbo.ArchivalInfo (NOLOCK) WHERE TableName = #TableName
DECLARE #SqlString nvarchar(2000)
DECLARE #ParamDef nvarchar(2000)
SET #SqlString = N'exec '+#SpName + ' #CriteriaParam'
SET #ParamDef = N'#CriteriaParam XML'
EXECUTE sp_executesql #SqlString ,#ParamDef, #CriteriaParam = #Criteria

stored procedure input parameter

i am creating a stored procedure in sql server 2008 such as this
-- the code
create procedure proce
#database varchar(50)
as
begin
select * from [#database].[dbo].[sometable]
end
the procedure is compiled
but when i execute the procedure using
-- here i execute it
execute proce 'somedatabase'
it throws an error
-- me gets error :(
Invalid object name '#database.dbo.sometable'
where am i going wrong???????
You cannot directly parameterized the tableName. The only way you can do that is to make a dynamic SQL Statement.
eg,
CREATE PROCEDURE proce #database VARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(500)
SET #SQLQuery = 'SELECT * FROM [' + #database + '].[dbo].[sometable]'
EXECUTE(#SQLQuery)
END
GO
Building Dynamic SQL In a Stored Procedure
You can go with this:
DECLARE #string AS NVARCHAR(500)
SET #string = 'select * from [' + #database + '].[dbo].[sometable]'
EXEC (#string)
More more info refer: Dynamic SQL
I don't believe variables are allowed in that context, use the following which I've just confirmed works with your procedure:
exec('select * from [' + #database + '].[dbo].[sometable]')

Creating SQL table using dynamic variable name

I want to create backup SQL tables using variable names.
something along the lines of
DECLARE #SQLTable Varchar(20)
SET #SQLTable = 'SomeTableName' + ' ' + '20100526'
SELECT * INTO quotename(#SQLTable)
FROM SomeTableName
but i'm getting
Incorrect syntax near '#SQLTable'.
It's just part of a small script for maintence so i don't have to worry about injections.
DECLARE #MyTableName sysname;
DECLARE #DynamicSQL nvarchar(max);
SET #MyTableName = 'FooTable';
SET #DynamicSQL = N'SELECT * INTO ' + QUOTENAME(#MyTableName) + ' FROM BarTable';
EXEC sp_executesql #DynamicSQL;
Unfortunately, you can't use bind variables for table names, column names, etc. IN this case you must generate dynamic SQL and use exec.
DECLARE #Script NVARCHAR(MAX);
SET #Script = N'SELECT * INTO SomeTableName_' + N'20100526' + N' FROM SomeTableName';
EXEC sp_executesql #Script
I've left the date separate as I assume you want to calculate it for every run.
You should look into using synonyms:
-- Create a synonym for the Product table in AdventureWorks2008R2.
CREATE SYNONYM MyProduct
FOR AdventureWorks2008R2.Production.Product;
GO
-- Query the Product table by using the synonym.
USE tempdb;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
GO
http://msdn.microsoft.com/en-us/library/ms177544.aspx
DECLARE #MyTableName nvarchar(20);
DECLARE #DynamicSQL nvarchar(1000);
SET #MyTableName = "FooTable";
SET #DynamicSQL = N'SELECT * INTO ' + #MyTableName + ' FROM BarTable';
exec #DynamicSQL;
this query is correct but just use single quote at the ("FooTable")='FooTable'