Build Stored Procedure that inserts data into a received table - sql

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.

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

Using a variable in insert command

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

How to insert dynamic regional text into a table in SQL Server using the stored procedure parameters

I know how to insert different regional text into database in SQL Server using the normal insert statement as below:
INSERT INTO Telugu (Title, Description, [Image])
VALUES (N'వారెవ్వా.. టాయిలెట్ కోసం ఎంతపని చేశారు ', N'వారెవ్వా.. టాయిలెట్ కోసం ఎంతపని చేశారు', '\Images\templatemo_image_02.jpg')
But I want the same operation to performed using stored procedure using the parameters. Can anyone suggest how I can do this?
Hope you want to insert the values with N. That can be achieve by dynamic query.
CREATE PROCEDURE InsertRegionalText (
#TitleText NVARCHAR(MAX),
#DescriptionText NVARCHAR(MAX),
#ImagePath NVARCHAR(MAX)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SqlQuery AS NVARCHAR(MAX) = '';
SELECT #SqlQuery = N'
INSERT INTO Telugu (Title, Description, [Image])
VALUES (N''' + #TitleText + ', N''' + #DescriptionText + ', ' + #ImagePath + ');'
--PRINT #SqlQuery
EXEC (#SqlQuery)
END
Thanks Every one for the Help.
I was able to solve the Issue.
If our table Columns datatype is Nvarchar then we don't need to prefix any 'N' Character to our stored Procedure Parameters.
I have added my tables Image below
Here is the stored Procedure which I have used:
CREATE PROCEDURE [dbo].[usp_UpdateSubCategoryDetails]
-- Add the parameters for the stored procedure here
#SubCategoryID INT,
#SCDetailsHeading NVARCHAR(300),
#SCDetailsDescription NVARCHAR(3000),
#IMAGE NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO tblSubCategoryDetails(SubCategoryID,SCDetailsHeading,SCDetailsDescription,[Image],IsActive)
VALUES(#SubCategoryID,#SCDetailsHeading,#SCDetailsDescription,#IMAGE,1)
SELECT SubCategoryID,SCDetailsHeading,SCDetailsDescription,[Image] FROM tblSubCategoryDetails
WHERE IsActive =1
END
OUTPUT:
1 ఫోటో స్టోరి: 40 లోనూ అదే మాయ ఫోటో స్టోరి: 40 లోనూ అదే మాయ ../images/FilmyImages/heroine_raashi_khanna-1920x1080.jpg

How to use parameters in sql queries (sp_executesql not working as per requirement)

I have used temporary tables plus temporary variables..
Now when my sql queries are having both temporary variables and table, i got to know sp_executesql not working because we can't use temporary tables in it
and standard execution won't take the variable parameters.
So it will be very helpfull if anyone can help me out with some other solution for it?
This is a sample code :
create procedure tryit
as begin
declare #temp as Table_Type;
declare #ghdhj as nvarchar(50)
set #ghdhj='TBVHTempSelectionTable';
declare #sqlstatement nvarchar(max);
set #sqlstatement=N'insert into #temp select * from '+#ghdhj+';';
exec sp_executesql #sqlstatement;
--,#temp='finalResultTable',#ghdhj='TBVHTempSelectionTable'
select * from #temp;
end
go
exec tryit
Create temporary table and then execute sp_executesql
If you create the temporary table first you should be able to access it in sp_executesql if you specify it explicitly
select *
into #peter
from (values (10), (10)) p(a);
exec sp_executesql N'insert into tempdb..#peter values (20), (20)';
select * from #peter;
-- Result
A
10
10
20
20
sp_executesql can accept table valued parameters, so you can pass a table variable to sp_executesql.
First, you need a table type defined on your database. You create table types using CREATE TYPE statement. For example:
CREATE TYPE dbo.CategoryTableType AS TABLE
(
CategoryID int,
CategoryName nvarchar(50)
)
GO
Once you have the table type you can pass table variables of that type to sp_executesql. For example:
DECLARE #Categories CategoryTableType
INSERT INTO #Categories
VALUES (1, 'Beverages'), (2, 'Confections')
EXEC dbo.sp_executesql
N'SELECT * FROM #Categories',
N'#Categories CategoryTableType READONLY',
#Categories
sp_executesql cannot access variables of any kind declared outside the sql statement passed to sp_executesql.
However sp_executesql can access to temporary tables created in the calling scope stack. For example:
CREATE TABLE #Categories (
CategoryID int,
CategoryName nvarchar(50)
)
INSERT INTO #Categories VALUES
(1, 'Beverages'), (2, 'Confections')
EXEC dbo.sp_executesql N'SELECT * FROM #Categories'
DROP TABLE #Categories
On the other hand the calling scope cannot access to temporary tables created in the sql statement passed to sp_executesql. For example the following code will fail with Msg 208, Level 16, State 0, Invalid object name '#Categories'.
EXEC dbo.sp_executesql N'
CREATE TABLE #Categories (
CategoryID int,
CategoryName nvarchar(50)
)
INSERT INTO #Categories VALUES
(1, ''Beverages''), (2, ''Confections'')'
SELECT * FROM #Categories
Also, the calling scope cannot access to any variable declared inside the sql statement passed to sp_executesql

SQL Server 2008: Insert variable into DML statements using Stored Procedure

I have the following procedure:
CREATE PROCEDURE [dbo].[Test1]
AS
BEGIN
INSERT INTO [My_Database].[My_Schema].[My_Table]
(...lists columns...)
SELECT ... lots of columns from joined query...
END
Instead of hardcoding "[My_Database].[My_Schema]", I now want to select it as a variable from a predefined table like this:
CREATE PROCEDURE [dbo].[Test1]
AS
BEGIN
SELECT #myDB = [My_DB] FROM [my_custom_table]
--INSERT INTO [My_Database].[My_Schema].[My_Table]
INSERT INTO #myDB.[My_Table]
(...lists columns...)
SELECT ... lots of columns from joined query...
END
It does not work if I use it like above. I need to use:
EXEC sp_executesql (entire_sql_statement_in_quotes)
My problem is that I have a lot of these procedures to change to using a variable instead of being hardcoded. It will take forever to convert each statement to a long string.
Is there some other way to do it? What am I missing?
Regards
One idea, you could drop and recreate a synonym using dynamic SQL at the beginning of each procedure, then you can leave each Insert statement as Insert Into MySynonym
DROP SYNONYM MySynonym -- Must create it first before running this bit!
DECLARE #sql nvarchar(max)
SET #SQL = 'CREATE SYNONYM MySynonym
FOR ' + #myDB + '.test1'
EXEC sp_Executesql #sql
INSERT INTO MySynonym
SELECT ...
This would give you a peice of code you could copy paste into each SP. If the table you are inserting into is different for each SP, you could declare that too and build it into your CREATE SYNONYM statement
SET #SQL = 'CREATE SYNONYM MySynonym
FOR ' + #myDB + '.' + #MyTable
to Truncate each table first you would need to use DynamicSQL also, as you cannot delete on a synonym
SET #SQL = 'Truncate Table ' + #MyTable
EXEC sp_Executesql #sql