Can I use dynamic sql in ASE to declare a cursor - dynamic-sql

I want to use dynamic sql to select the database name for a cursor. Is this or something similar possible using sybase ASE?
create procedure myproc
#dbname = varchar(20) = null as
declare mycur cursor for select #dbname..mytable
... use cursor
go

You can create dynamically a temp table
something like
create procedure myproc (#dbname ....)
as
exec ('SELECT ...... into tempdb..test FROM '+#dbName+'..mytable')
-- and then
DECLARE Cursor1 for tempdb..test
open cursor
etc

To use dynamic sql, first create a temp table using
Create table #mytemptab (col1 …, col2 …)
Construct the dynamic sql using the following method
DECLARE #sqlstr VARCHAR(5000)
SELECT #sqlstr=’SELECT col1, col2 FROM ‘+#table
Now insert into the temp table you created (make sure it is of the same datatypes as the sql output)
SELECT #sqlstr= ‘Insert into #mytemptab (col1, col2 …) ‘+#sqlstr
Execute sql statement (to insert data into temp table)
EXECUTE (#sqlstr)
Now use the temp table in the cursor
DECLARE mycursor CURSOR FOR SELECT col1, col2 FROM #mytemptab
OPEN…
FETCH…
……

Related

Inserting into a user-defined table type via a dynamic query in SQL Server?

I have a user-defined table type tyAnalysisNumbers. I need to populate my user defined data type within a stored procedure with a SELECT statement and I am struggling to get that working within my stored procedure.
The following ways I have tried do not work
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM ' + #someTable);
I get this error:
An INSERT EXEC statement cannot be nested
I am unsure how to insert into my custom table via a select statement.
Can anyone help me accomplish this?
An INSERT EXEC statement cannot be nested
Above error is self explanatory. Please look at below scenario:
For example, we have one procedure which inserts data in table type and return result.
CREATE PROCEDURE uspInsertData1
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM someTable');
select * from #MyTable
END
Now, let's say we have another procedure which will call above procedure and again insert data in another table.
CREATE PROCEDURE uspInsertData2
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO sometable
EXEC uspInsertData1
END
Now, if you execute 1st procedure it will work fine but if you execute second procedure you will get this error.
An INSERT EXEC statement cannot be nested.
Because now you have nested EXEC statements.
I suggest to finish your work in single stored procedure if possible.
Try it like this:
DECLARE #MyTable tyAnalysisNumbers;
SELECT * INTO #Temp FROM #MyTable;
DECLARE #tblName AS SYSNAME = (SELECT name FROM sys.tables WHERE name = #someTable);
EXEC ('INSERT INTO #Temp SELECT * FROM ' + #tblName);
This also addresses the SQL Injection problem.

How to insert data into another table from a variable in SQL Server stored procedure

I would like to insert the data from a variable (which is a table name) into another table inside a stored procedure. But when I try altering the stored proc I get an error. What am I doing wrong?
SQL:
INSERT INTO DBNAME..Table (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM #Tablevariable;
Error:
Must declare the table variable "#Tablevariable".
#Tablevariable is already declared in my stored procedure.
You cannot have the table-name be a variable. You could do something like this in the stored procedure:
DECLARE #Tablevariable nvarchar(50) = 'MyTableName'
DECLARE #SQL nvarchar(MAX)
SET #SQL = 'INSERT INTO DBNAME..Table (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM ' + #Tablevariable
EXECUTE (#SQL)
I don't think there is a way of doing FROM #TableVariable. I think instead you'd need to do either:
Stick a case statement in there so if #TableVariable = 'Customers' select from customers table. The problem with is though every time you create a new table you must update your stored proc.
Build out the text as a string within SQL: DECLARE sqlCommand VARCHAR(MAX) = 'Select blah blah blah FROM ' + #TableVariable (or something like that). Then call exec(sqlCommand). The problem with this is though, you wont' get query optimization on the sqlCommand.

How to use the return table data of one procedure in another procedure?

I had a procedure it will return data from a temporary table.The temporary table structure may varies depends on the input parameter of the procedure.This procedure is a general procedure so i cant modify this one.
My requirement is that i want to use the return temporary table data to do some calculation from another procedure.Is it possible to achieve this one????
requirement is some thing like this
Create Procedure Proc2 ( #Condition int)
As
BEGIN
execute #temp = Proc1 input1,input2
select * from #temp where column1 = #Condition
END
This Proc1 is using in some other procedures also so i cant include the condition inside Proc1.
Am using SQL SERVER 2008 R2
Thejus T V
You need to create a temporary table and use like this
Create Procedure Proc2 ( #Condition int) As
BEGIN
create table #temp(col1 int, col2,....) -- similar to reseultset of proc1
insert into #temp
execute Proc1 input1,input2
select * from #temp where column1 = #Condition
END
If the column names are unknown you can use OPENROWSET
Select
*
from
OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..proc1')
If you know the structure being returned by the procedure then you can simply create a temp table and insert the data into that temp table from the stored procedure result set.
Create Table #Temp (Col INT , Col2 INT)
INSERT INTO #Temp
Exec Proc1 input1,input2
But since you have mentioned you don't know the exact structure of the table begin returned from the stored procedure you can use OPENQUERY to manipulate further the result set of a stored procedure something like this....
SELECT *
FROM OPENQUERY(YOURSERVERNAME, 'Proc1 input1,input2')
where column1 = #Condition

Insert sql query result inside stored procedure in temp table

I have stored procedure in which i store whole query inside string and then execute that. Now i want to store that execute result into temporary table for further processing.
Something like below :
Exec #Mainsql -- this returns me query result and i need to insert its result to temp table
I tried something like this:
Select * Into #TempTable
From
Exec #MainSQL
But It is lacking in syntax i guess.
So, i need result of mainsql into temptable
Try this:
CREATE TABLE #TempTable AS
Exec #MainSQL
You must create Temp Table first, You have to define all columns which will be returned from procedure, if you need to insert data using Stored Procedure:
CREATE TABLE #TempTable (Col1 INT, Col2 VARCHAR(10))
INSERT INTO #TempTable
EXEC [ProcedureName]
Another option is to use OPENROWSET, if you do not know returned columns :
SELECT * INTO #TempTable
FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;', 'EXEC DBName.Schema.ProcedureName')

Execute store procedure like a "table" for SELECT operator (MS SQL SERVER)

Is it possible to execute store procedure
like a "table" for SELECT operator (MS SQL SERVER)?
Something like
SELECT TotalSum FROM exec MyStoreProcedure '2011/11/01', '2011/11/01'
I mean somehow integrate it into the SELECT operator?
Thank you!
Thanks guys!
The solution what I did is based on your answers:
declare #result table (f1 varchar(20),f2 varchar(20), CodProducto int, NomProducto varchar(1000), Costo decimal, Cantidat int, Total decimal)
INSERT INTO #result exec MyStoreProcedure '20111201', '20111201'
select * from #result
I supposed your proc returns several columns and you just want one, right?
small workaround is to add the result of the proc to a table variable and then select from it
create proc proc1 as
select 1 as one, 2 as two
declare #result table (one int, two int)
insert into #result
exec proc1
select one from #result
This would be better as a function rather than a stored procedure.
create function dbo.TestTable
(#var1 bit)
returns table
AS
RETURN
( select *
from INFORMATION_SCHEMA.TABLES
where #var1 = 1
);
select * from
dbo.TestTable(1)
Not directly (or without altering the stored procedure to be a table-valued function).
But you could do this:
INSERT INTO SomeTempTableWithSchemaMatchingTheSproc (...)
EXEC MyStoredProcedure
SELECT * FROM SomeTempTableWithSchemaMatchingTheSproc
SQL Server 2005 onwards, you can also use a table variable.
This works for me:
CREATE VIEW dbo.vw_xxx
AS
select * from openquery(YOURSERVERNAME, 'exec [sp_xxx] '''','''','''','''','''','''' ')