stored procedure input parameter - sql

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]')

Related

Exec stored procedure with OpenQuery & parameter

Stored procedure as below. It is using a linked server to Oracle.
ALTER PROCEDURE [dbo].[SVOPS_ZsmartPaymentView]
(#param01 VARCHAR(255))
AS
BEGIN
SELECT *
FROM OPENQUERY(ZSMART_PROD, 'SELECT BANK_SN FROM CC.V_PAYMENT WHERE BANK_SN=''#param01''')
END
If I call the stored procedure with parameters as shown below, the result is empty:
EXEC [dbo].[SVOPS_ZsmartPaymentView] #param01 = 'T131612073600'
But if I run the statement directly like below, there is result.
SELECT *
FROM openquery(ZSMART_PROD, 'SELECT * FROM CC.V_PAYMENT WHERE BANK_SN=''T131612073600''')
Any idea why it returned empty result if executed using the stored procedure?
Try this:
ALTER PROCEDURE [dbo].[SVOPS_ZsmartPaymentView]
(#param01 VARCHAR(255))
AS
BEGIN
SELECT *
FROM OPENQUERY(ZSMART_PROD, 'SELECT BANK_SN FROM CC.V_PAYMENT WHERE BANK_SN=''' + #param01 + '''')
END
I follow the sample from https://support.microsoft.com/en-us/help/314520/how-to-pass-a-variable-to-a-linked-server-query.
And it works.
Pass Basic Values
When the basic Transact-SQL statement is known, but you have to pass in one or more specific values, use code that is similar to the following sample:
DECLARE #TSQL varchar(8000), #VAR char(2) SELECT #VAR = 'CA' SELECT
#TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM
pubs.dbo.authors WHERE state = ''''' + #VAR + ''''''')' EXEC (#TSQL)
Thanks.

Execute openrowset stored procedure, parameter use

Little bit of background information:
I have a stored procedure, lets call it SP1. SP1 calls another stored procedure: SP2. SP2 calls another stored procedure: SP3.
Now, the first stored procedure (SP1) returns a resultset. The resultset are parameters for SP2, this is done with a cursor.
Because of these nested inserts and executes, i have to use an openrowset dynamic SQL string to execute my stored procedures.
This is my query:
DECLARE #P_Source varchar(255) = 'test'
DECLARE #P_Location varchar(255) = 'test'
DECLARE #sql varchar(max)
SET #sql = 'INSERT INTO #tmp
SELECT *
FROM OPENROWSET (
''SQLOLEDB'',
''Server=(local);TRUSTED_CONNECTION=YES;'',
''set fmtonly off
EXECUTE dbo.SP1
#P_Source = '''''+#P_Source+'''''''
,#P_Location = '''''+#P_Location+'''''''
)'
exec(#sql)
(I have ofcourse created the table #tmp). I have more parameters to be exact (12), all varchar, but I left them out to not make it messy.
I'm getting the following error
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ','.
am I using the openrowset command in the correct way with the corresponding procedure parameters?
All those quotes get confusing. By doing select #sql prior to the exec you can see what SQL Server is going to try and do. Based on the query you've provided #sql currently contains:
INSERT INTO #tmp
SELECT *
FROM OPENROWSET (
'SQLOLEDB',
'Server=(local);TRUSTED_CONNECTION=YES;',
'set fmtonly off
EXECUTE dbo.SP1
#P_Source = ''test'''
,#P_Location = ''test'''
)
To help you build up to the final solution you could try having a dummy SP1 that takes two numeric parameters - that'll eliminate some quotes for you to worry about. Once you have that working you can proceed to add string parameters until you get what you want.
For sql linked server use OPENQUERY
https://learn.microsoft.com/en-us/sql/t-sql/functions/openquery-transact-sql
and sp_executesql
DECLARE #P_Source varchar(255) = 'test'
DECLARE #P_Location varchar(255) = 'test'
DECLARE #SQL NVARCHAR(MAX) = '',
#QUERY NVARCHAR(MAX) = '',
#Params NVARCHAR(500) = N'DECLARE #P_Source VARCHAR(255),#P_Location VARCHAR(255); ',
#ParamsValue NVARCHAR(500) = N'SELECT #P_Source = '''''+#P_Source+''''', #P_Location = '''''+#P_Location+''''';'
SET #Query = N'set fmtonly off; EXECUTE dbo.SP1 #P_Source, #P_Location'
SET #SQL = 'SELECT * FROM OPENQUERY([Local],'' sys.sp_executesql ' + #Params + #ParamsValue + #Query +''' )'
INSERT INTO #Tmp
EXEC (#SQL)

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

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

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.

Procedure to insert Xml Into Sql Server -- Must Declare Scalar Variable

I am using the below procedure to try and insert xml via the filepath into a xml column. I am getting an error must declare scalar variable for ForeignId. Is there a better way of doing what I am trying to do, or am I on the right path?
Here is the procedure
ALTER PROC [dbo].[InsertXml] #path nvarchar(100)
,#ForeignId uniqueidentifier
AS
BEGIN
SET NOCOUNT ON
DECLARE #SQL nvarchar(4000) =
'INSERT INTO XmlTable(XmlId
, ForeignId
, TestXml)
SELECT NEWID()
, #ForeignId
,* FROM OPENROWSET(
BULK ''' + #path + ''',
SINGLE_BLOB) AS x;'
EXECUTE(#SQL);
RETURN ##ERROR;
END
When you're executing the SQL statement using EXECUTE(SQL) it has no access to the #ForeignId value
One way to solve this is to use sp_excuteSQL and do this instead of EXECUTE(#SQL);
DECLARE #ParmDefinition nvarchar(500);
SET #ParmDefinition = N'#ForeignId uniqueidentifier';
EXECUTE sp_executesql #SQL, #ParmDefinition, #ForeignId ;
You could also just concatenate the #ForeignId to your sql string but I can't recall if there are issues with that when using a uniqueidentifier