Using a variable in insert command - sql

I would like to use a variable in my INSERT command. This variable includes result value from a storedprocedure:
declare #File as varbinary(max)
exec #File=[dbo].[MySp]
but If I use #File in an INSERT command, another value of is written in table
insert into [dbo].[Plots] values ('test', #File)
My Stored Procedure:
CREATE PROCEDURE [MySp]
AS
BEGIN
EXEC sp_execute_external_script #language = N'R'
, #script = N'_RCODE_'
, #input_data_1 = N'_INPUT_QUERY_'
,#output_data_1=N'OutputDataset'
--- Edit this line to handle the output data frame.
WITH RESULT SETS (([plot] VARBINARY(max)));
END;

Your using of Stored Procedure is wrong.
There is a recordset on first screenshot, but after execution exec #File=[dbo].[MySp] you don't have the recordset in variable #File.
You got
#return_status
in #File
#return_status Is an optional integer variable that stores the return
status of a module. This variable must be declared in the batch,
stored procedure, or function before it is used in an EXECUTE
statement.
The right query can be like this:
declare #File as varbinary(max)
DECLARE #Table TABLE
(
plot VARBINARY(MAX)
)
INSERT #Table
exec [dbo].[MySp]
SELECT #File = MAX(plot)
FROM #Table
insert into [dbo].[Plots] values ('test', #File)

Your EXEC call is getting the result code of the SP, which is 0 for success, I suppose, in the absence of an explicit return statement.
See this answer for more details on how to capture actual data from your SP: https://stackoverflow.com/a/3963991/16777

Related

Dynamic SQL throws error complaining scalar variable is not defined

I am copying my bulk data to SQL Server (table name: TmpTable) via C# code and then I want to update the table with following stored procedure:
ALTER PROCEDURE dbo.sp_Update_Locations
(#lupdatedNoRow VARCHAR(10) OUT)
AS
SET NOCOUNT ON
BEGIN
DECLARE #mttblfaximages3_sql NVARCHAR(500) ='UPDATE testAdmin.dbo.mttblFaxImages2 set fRemoteStorageLocation = temp.RemoteStorageLocation, fRemoteImageName = temp.RemoteImageName from testAdmin.dbo.mttblFaxImages2 T INNER JOIN #TmpTable Temp ON (T.fFaxId=Temp.PrimaryId AND T.fFaxPageId=Temp.SecondaryId); DROP TABLE #TmpTable;SELECT #lupdatedNoRow = cast(##rowcount as VARCHAR)'
EXEC sp_executesql #mttblfaximages3_sql
select #lupdatedNoRow
END
I see update works fine but c# throws exception after that
Must declare the scalar variable "#lupdatedNoRow"
I want to return the number of rows updated.
How I should modify my stored procedure to return number of rows updated?
you need to define & pass the variable #lupdatedNoRow into the sp_executesql
EXEC sp_executesql #mttblfaximages3_sql,
N'#lupdatedNoRow varchar(10) OUTPUT',
#lupdatedNoRow OUTPUT
select #lupdatedNoRow

Build Stored Procedure that inserts data into a received table

I built a procedure that receives a parameter with a table name, and inserts into that table, new data.
CREATE PROCEDURE sp_Ins
#tabela NVARCHAR(80)
AS
INSERT INTO #tabela (CustomerID, CustomerPW)
VALUES (1, '123')
GO
CREATE PROCEDURE SP1
#tabela NVARCHAR(80)
AS
EXEC sp_Ins #tabela
GO
EXEC SP1 'CustomerPW'
But I get this message:
Must declare the table variable #tabela
How can I declare the received parameter to recognize the parameter as a table?
Sorry, you need to use dynamic SQL. You cannot insert into a string:
CREATE PROCEDURE sp_Ins (#tabela nvarchar(80))
AS
BEGIN
declare #sql nvarchar(max) = '
INSERT INTO [t](CustomerID, CustomerPW)
VALUES (1, ''123'')
;
set #sql = replace(#sql, '[t]', QUOTENAME(#tablea));
exec sp_executesql #sql;
END;
Note: You may not want quotename() if tablea could use multipart naming.

Execute stored procedure output script

I have a stored procedure that produces a script of insert statements as result.
I want to execute those statements so that I can fill the data in my table
For example :
SET NOCOUNT ON
INSERT INTO table ([UID], [Name])
VALUES ('1000002', 'name'),
('1000004', 'name2')
The stored procedure return this as result, I want to execute this script how do I do it?
If I understand correctly, the above code is printed out when the stored procedure runs.
I would start by modifying the stored procedure to take an output parameter. Stored procedures "return" integer values, not messages. They happen to print things out, but it is not good to depend on that behavior.
Then, you can simply do:
declare #str nvarchar(max);
exec <stored procedure> #str output;
exec #str;
I suspect there might be a better way to structure the code. Having stored procedures return code should only be done when you really understand what you are doing. I don't think I've ever written code where a stored procedure would return an insert statement. It seems better to run dynamic SQL in the stored procedure itself.
EDIT:
You can capture the output of the stored procedure as well:
declare #t table (id int identity, line nvarchar(max));
insert into #t(line)
exec(<stored procedure>);
Then, you can concatenate the values. You can use XML for this purpose, but I think this will work:
declare #str nvarchar(max);
set #str = '';
select #str = #str + line + ' '
from #t
order by id;
exec #str;
Thanx All of you but following is the way i should have done
USE db1;
SELECT *
INTO [table]
FROM [db2].[dbo].[table]
it helps me to copy a table

Save result of stored procedure to variable

Given a stored procedure like the one shown below:
CREATE PROCEDURE [dbo].[GetBusinessUnitSysNameAndGroupNames]
#ModelAfter varchar(100),
#BusinessUnitSystemName varchar(100) OUT,
#GroupsName varchar(4000) OUT
AS
BEGIN
if (#ModelAfter = 'Corporate')
BEGIN
SET #GroupsName = 'Admins'
SET #BusinessUnitSystemName = 'AcmeOutdoors'
END
else if (#ModelAfter = 'Retailers')
BEGIN
SET #GroupsName = 'Sellers'
SET #BusinessUnitSystemName = 'AcmeShoppers'
END
END
When I run from the SQL Studio command line:
EXEC [dbo].[GetBusinessUnitSysNameAndGroupNames] '~ModelAfter~', 'acmeoutdoors', 'admins'
I just get a result in the message panel like Command(s) completed successfully. But what I would like to see the actual result, not just a success message. Something like shown below(which doesn't work, just my idea).
DECLARE #Result varchar(max)
SET #Result = EXEC [dbo].[GetBusinessUnitSysNameAndGroupNames] '~ModelAfter~', 'acmeoutdoors', 'admins'
PRINT #Result
Returning Data by Using OUTPUT Parameters
If you specify the OUTPUT keyword for a parameter in the procedure
definition, the stored procedure can return the current value of the
parameter to the calling program when the stored procedure exits. To
save the value of the parameter in a variable that can be used in the
calling program, the calling program must use the OUTPUT keyword when
executing the stored procedure.
DECLARE #Result1 varchar(max), #Result2, varchar(max)
EXEC [dbo].[GetBusinessUnitSysNameAndGroupNames] 'Corporate', #Result1 OUT, #Result2 OUT
PRINT #Result1
PRINT #Result2

Dynamically get all parameter values in stored procedure

Is there any way to get all parameter values from a stored procedure dynamically?
In other words, iterate through all parameters in one stored procedure to get their values into one string. This is for a unified logging process for a bunch of stored procedures.
I can get the names of parameters:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. I've generated a command with included parameter, but EXEC can't execute command.
#cmd = 'SELECT '#UserID' + CONVERT(NVARCHAR(MAX), #UserID)
+ '#Date' + CONVERT(NVARCHAR(MAX), #Date)'
EXEC #cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure?
Since SQL Server 2014 there is sys.dm_exec_input_buffer a table valued function with an output column event_info that gives the full execution statement (including parameters).
I use this for error logging in stored procedures.
For example:
--include this inside the stored procedure
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print #statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
select #params