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

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.

Related

Is it possible to call a stored procedure within an INSERT statement?

In a nutshell, here's what I'm trying to do:
CREATE PROCEDURE sp_insertingStuff
#value1
AS
INSERT INTO [my_table] (column1, column2)
VALUES (#value1, execute sp_anotherSP)
GO
What I need to know is: is it possible to execute a stored procedure from within an INSERT statement like that? If there's a better way to do this I'm open to the advice. The reason I need to do something like this is because I need to run some IF statements to get the value for that second column.
execute the second one just above the insert statement inside the first sp
like:
CREATE PROCEDURE sp_insertingStuff
#value1
AS
declare #value2 int
exec #value2 = sp_anotherSP
INSERT [my_table] (
column1,
column2
)
VALUES (
#value1,
#value2
)
GO
You can not execute a sp in the VALUES part. You have to execute and get the return/out value before insert, like this.
CREATE PROCEDURE sp_insertingStuff
#value1
AS
DECLARE #anotherValue INT
execute #anotherValue = sp_anotherSP
INSERT [my_table] (
column1,
column2
)
VALUES (
#value1,
#anotherValue
)
Add OUTPUT parameter in you sp_anotherSP
https://technet.microsoft.com/en-us/library/ms187004(v=sql.105).aspx
and
DECLARE #Val <type>
EXEC sp_anotherSP #Val OUTPUT
... insert using #val
One mentioned solution is to add an OUTPUT parameter. Another is to rewrite your stored procedure as a function, as long as your stored procedure doesn't already UPDATE/INSERT/DELETE any data.
Yes this can be done by making the temp table in the insert sp.
then call the sp that you want to call and store the value in the temp table and then you can use that temp table values in your sp and at last drop that temp table

Creating a stored procedure using variables

Is there any good way to do this, or am I just heading in the wrong direction? I would like to create a stored procedure inside an SQL script. I would like to have variables declared at the beginning of the script so that I can create the SPROCs to use in different contexts/servers.Here is what I would like to do (I know this obviously doesn't work, but I'm looking for any ideas of an alternative)..
DECLARE #golbalValue = 'SomeValue'
GO
CREATE PROCEDURE [dbo].[MyStoredProcedure](
AS
BEGIN
SELECT * FROM Mytable WHERE MyCol = #globalValue
END
GO
What you could do is use a scalar function for the variable
create function f ()
returns varchar(20)
as
begin
return 'some value'
end
go
then use it in your procedure
create proc p ()
as
begin
select *
from my_table
where col = f()
end
go
another possibility which is perhaps more appropriate is to use sqlcmd here's an example.
From what I understand, you need to create stored procedures with set value from your parameters. You don't want input parameters in the stored Procedures though. Second, you want to switch database contexts. So I think you'll need a tempTable for your parameters and some dynamic SQL. Try this out:
IF OBJECT_ID('tempdb..#globalParam') IS NOT NULL
DROP TABLE #globalParam;
IF OBJECT_ID('AdventureWorks2012.dbo.myTable') IS NOT NULL
DROP TABLE AdventureWorks2012.dbo.myTable
IF OBJECT_ID('Master..myTable') IS NOT NULL
DROP TABLE Master..mytable
--Create your data tables
SELECT 'SomeValue' AS col1 INTO AdventureWorks2012.dbo.myTable;
SELECT 1000 AS col1 INTO master.dbo.myTable;
CREATE TABLE #globalParam(
ParamName VARCHAR(100),
val SQL_VARIANT --SQL_Variant is designed to hold all data types.
);
--Here are your globalParams
DECLARE #globalParam1 VARCHAR(100) = 'SomeValue';
DECLARE #globalParam2 INT = 1000;
--Load your parameters into a table. Might have to cast some of your parameters to SQL_Variant
INSERT INTO #globalParam
VALUES ('globalParam1',#globalParam1),
('globalParam2',CAST(#globalParam2 AS sql_variant));
GO
--Switch database context
USE AdventureWorks2012
GO
--Variable to hold CREATE PROC
DECLARE #sql VARCHAR(MAX);
--Set #SQL with parameter value from #globalParam
SELECT #sql =
'CREATE PROCEDURE dbo.myStoredProc AS
BEGIN
SELECT * FROM myTable WHERE col1 = ''' + CAST(val AS VARCHAR(100)) + '''
END'
FROM #globalParam
WHERE ParamName = 'globalParam1'
--Execute to create the stored procedure
EXEC(#sql)
--Execute it to see if it works
EXEC dbo.myStoredProc
--Switch context. Repeat same steps
USE master
GO
DECLARE #sql VARCHAR(MAX);
SELECT #sql =
'CREATE PROCEDURE dbo.myStoredProc AS
BEGIN
SELECT * FROM myTable WHERE col1 = ''' + CAST(val AS VARCHAR(100)) + '''
END'
FROM #globalParam
WHERE ParamName = 'globalParam2'
EXEC(#sql)
EXEC dbo.myStoredProc
--Cleanup
DROP PROCEDURE dbo.myStoredProc;
USE AdventureWorks2012
GO
DROP PROCEDURE dbo.myStoredProc;
You cannot do what you want. T-SQL doesn't have the concept of global variables. One method is to store values in a "global" table and then reference them as needed. Something like:
create table GlobalParams (
name varchar(255) not null primary key,
value varchar(255) not null
);
create procedure . . .
begin
. . .
declare #value varchar(255);
select #value = value from Globalparams where name = 'name';
select *
from Mytable
where MyCol = #value;
. . .
end;
Note: this is a simplistic example that only allows variables whose type is a string.
You can also wrap the logic in a user-defined function, so the call looks like:
select *
from Mytable
where MyCol = udf_GlobalLookup('name');
It is rather rare to need global parameters that are shared among different stored procedures. Such a global context can be useful, at times, for complex systems. It is unlikely that you need all this machinery for a simple application. An alternative method, such as just passing the parameters in as arguments, is probably sufficient.

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

Pass select result as parameter of stored procedure

I have a T-SQL stored procedure with the following parameters
CREATE PROCEDURE [dbo].[SaveData]
-- Add the parameters for the stored procedure here
#UserID varchar(50),
#ServiceID varchar(50),
#param1 varchar(50),
#param2 varchar(50),
#endDate datetime
AS BEGIN
.
.
-- my code --
I want know if it is possible to pass a result of select as parameter:
exec SaveDate (SELECT player.UserID,player.ServiceID, 'no','no',GETDATE()
FROM player)
I tried something like this, but it does not work.
1.One way is:
a) Declare your variables
b) Assign values to them with a single select statement
c) Execute the procedure passing the local variables
d) Execute the following in a loop using WHILE or CURSOR in order to apply this for all rows in TABLE1
DECLARE #param1 <DATATYPE>, #param2 <DATATYPE>, ...
SELECT TOP 1 #param1 = col1, #param2 = col2, ...
FROM TABLE1
WHERE <where_clause>
EXEC SaveDate #param1, #param2, ...
2.Other way is to define your own table type, fill it, and pass it to procedure. However this requires changing a little bit your stored procedure (in params list your custom type should be followed by READONLY):
CREATE TYPE [dbo].[TYPENAME] AS TABLE(
[ID] [int] NOT NULL,
...
)
GO
DECLARE #myTypeVar TYPENAME;
INSERT #myTypeVar
SELECT col1, col2, ...
FROM TABLE1
EXEC SaveData #myTypeVar
The SELECT query you wrote in your example would probably bring back multiple rows (your SELECT does not feature a WHERE clause or a TOP(n)). If your intention is to be able to have your procedure engage a "tabular" set of parameters, from SQL Server 2008, you are able to use table valued parameters.
This involves creating a user defined table table and will almost undoubtedly mean adjusting the logic inside the stored procedure.
Hope this helps :)
See http://msdn.microsoft.com/en-us/library/bb510489(SQL.100).aspx
for more information.

Can I use dynamic sql in ASE to declare a cursor

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…
……