I am creating a stored proc in MS SQL Server 2008.
Here in my SP, after an insert statement, an identity value for that row inserted will be
generated. I am using that in another insert Statement.
#SID int
insert into table1(SNAME) values('Sname')
set #SID=SCOPE_IDENTITY()
insert into table2(SID)values(#SID)
here, my doubt is , is it required to add #SID as a parmeter in C# code.
how to declare a variable that do not expect any parameter ? since it is getting the value
from the SP itself..
Please help
Change the sql from
#SID int
to
DECLARE #SID int
Have a look at DECLARE #local_variable (Transact-SQL)
Variables are declared in the body of a batch or procedure with the
DECLARE statement and are assigned values by using either a SET or
SELECT statement. Cursor variables can be declared with this statement
and used with other cursor-related statements. After declaration, all
variables are initialized as NULL, unless a valu is provided as part
of the declaration.
Declaring variable in SQL Server
Declare #SID int --Declaring variable in SQL Server
insert into table1(SNAME) values('Sname')
set #SID=SCOPE_IDENTITY()
insert into table2(SID)values(#SID)
my doubt is , is it required to add #SID in C# code
The question is do you want this identity to be returned as an output parameter to your class?
If YES then you will have to pass it as an output parameter. Like
#SID INT OUTPUT -- as stored procedure parameter
If NO then all the variables that are required locally within the stored procedure will be declared locally. You only need to change
#SID int
To
DECLARE #SID int
CREATE PROCEDURE SPNAME
#PARAM1 INT,
#PARAM2 VARCHAR(10),
.
.
AS
BEGIN
DECLARE #SID AS int
insert into table1(SNAME) values('Sname')
set #SID=SCOPE_IDENTITY()
insert into table2(SID)values(#SID)
END
For Oracle and DB2 declaring variable is,
CREATE OR REPLACE PROCEDURE Proc1()
IS
Declare
myName in varchar;
STMT VARCHAR(4000);
BEGIN
Select fname into myName from student where fname='x'; // is returning unique value
END;
Related
I am new to MySQL and I am trying to port some stored procedures from SQL Server. I created a basic stored procedure with parameter passing in MySQL.
The stored procedure simply takes a parameter and executes a 'drop if exist' based on the parameter supplied.
When running in MySQL results in an error below.
Seems that somehow, the parameter passed 'mytablename' into the stored procedure is executed as part of the statement instead of a parameter.
Any advice?
SQL statement:
call mydb.spDroptableifexist('customerdata');
Results:
0 row(s) affected, 1 warning(s): 1051 Unknown table 'mydb.mytablename'
This is the stored procedure:
USE `mydb`;
DROP procedure IF EXISTS `spDroptableifexist`;
DELIMITER $$
USE `mydb`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `spDroptableifexist`(IN mytablename VARCHAR(255))
BEGIN
drop table if exists mytablename;
END$$
DELIMITER ;
From the manual:
User variables are intended to provide data values. They cannot be
used directly in an SQL statement as an identifier or as part of an
identifier, such as in contexts where a table or database name is
expected
To use a variable as a table name, you need to prepare a statement and execute it:
SET #sql = CONCAT('DROP TABLE IF EXISTS ', mytablename);
PREPARE stmt FROM #sql;
EXECUTE stmt;
I am using the following technologies:
MS SQL 2008 R2
Visual Studio 2010
Silverlight project
LINQ to SQL
When dragging a stored procedure into the data model, and the stored procedure returns an OUTPUT parameter, it works fine. However when the stored procedure returns a result set created with dynamic SQL I receive the following error:
"Unknown Return Type, The return type for the following stored procedure could not be detected."
If the stored procedure does not use dynamic SQL, it works fine.
(For example: SELECT column1 from table2)
The stored procedure however uses dynamic SQL to query a specified view for the data. Simplified below for illustration purposes:
CREATE PROCEDURE GetViewData
#ViewName nvarchar(150)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql nvarchar(MAX)
SET #Sql = 'SELECT Column1, Column2, Column3 FROM' + #ViewName
EXEC sp_executesql #Sql
END
Instead of returning the result set directly, I can place the result set into a temp table. This however gives the same error.
According to the article from Ritesh, when placing the result set into a table type variable this should do the trick, however this is not possible in dynamic sql as the scope is only within the executed dynamic sql.
Ritesh's article:
http://riteshkk2000.blogspot.com/2010/08/error-unknown-return-type-return-types.html
Upon further investigation I realized that the meta data received by LINQ to SQL does not contain the necessary information to define the type.
Apparently with SQL 2012 this can be resolved by using "WITH RESULTS SET" to actually define the meta data manually.
I resolved this by creating another stored procedure, calling GetViewData without using dynamic SQL and populating a table type variable:
CREATE PROCEDURE CallGetViewData
#ViewName nvarchar(150)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ViewResultSet TABLE
(
column1 nvarchar(50),
column2 int,
column3 float
)
INSERT INTO #ViewResultSet
EXEC GetViewData #ViewName
SELECT column1, column2, column3 FROM #ViewResultSet
END
Now when I drag stored procedure CallGetViewData into the data model, it detects the return type correctly.
One trick you can try is to manually create a model that represents the shape of the object that the Stored Proc will return. Then using the designer, don't drag the proc into the method pane, but rather drop it on the type you created manually. LINQ to SQL will then use that class as the result type.
If you already have the method defined for the stored proc, you can change the Return Type using the F4 property window to any type that matches the result shape that you've defined in the model.
I need to insert Tamil language into SQL Server 2005. I have tried using Insert or Update query, it worked fine. While going to stored procedure, I don't know how to pass the parameter.
ALTER PROCEDURE [dbo].[spr_Sam]
#Row_Id int = NULL,
#Description_Ta nvarchar(MAX) = null
AS
BEGIN
update tblTest set
Description_Ta = #Description_Ta
where Row_Id = #Row_Id
END
exec [dbo].[spr_Sam] 2, 'பெண்டிரேம்';
If I execute this it gets inserted as ?????.
exec [dbo].[spr_Sam] 2, N'பெண்டிரேம்';
If I execute this it gets inserted correctly.. but I don't know how to pass that 'N' from my C# Application. I used a text-box to get that Description_Ta parameter.
C# should add the N automatically if you use SqlDbType.NVarChar for SQLParameter
You must be using SqlDbType.VarChar of course
The MSDN doc for SqlDbType states (my bold)
VarChar: A variable-length stream of non-Unicode characters...
...
NVarChar: A variable-length stream of Unicode characters...
Here is the correct update statement:
update tblTest
set Description_Ta = #Description_Ta
where Row_Id = #Row_Id;
You don't need single quotes around a variable.
But, I think the posting is confused. To call the procedure use:
exec [dbo].[spr_Sam] 2, N'பெண்டிரேம்';
To modify it:
ALTER PROCEDURE [dbo].[spr_Sam]
#Row_Id int = NULL,
#Description_Ta nvarchar(MAX) = null
AS
BEGIN
update tblTest
set Description_Ta = #Description_Ta
where Row_Id = #Row_Id;
END;
You shouldn't have arguments when you define the stored procedure.
I'm aware that I can use a table value parameter as another option and I was already able to implement it. The reason I'm trying to use this approach(Table variable not Table value) is because I'm studying and I want to learn other ways on how to insert to database through a stored procedure.
Here's the current query I have:
CREATE PROCEDURE TVar
(
DECLARE #TblVar TABLE
(Product nvarchar(max), Qty int)
)
AS
Insert Into sample_tbl Select * FROM #TblVar
Is it possible to have this kind of approach wherein in the C# code I will use a datatable to pass as a parameter which can be done when using a table value parameter. I'm having errors when execute the query .
Here's the error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'DECLARE'.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.
Yes. You can use a table value parameter as a parameter to a stored procedure, and you can call from C#.
You need to separately declare a TABLE TYPE:
CREATE TYPE MyTableType AS TABLE
(
Product nvarchar(max),
Qty int
);
GO
and then use like so:
CREATE PROCEDURE TVar
(
#TblVar as dbo.MyTableType READONLY
)
AS
...
These articles show how to build a .NET DataTable to call the stored procedure from C#:
C# and Table Value Parameters
Table Value Parameters in SQL Server 2008 and .NET (C#)
create procedure InsertQuestionEntry
#round_name varchar(40),
#question varchar(100),
#answer varchar(40),
#option1 varchar(20),
#option2 varchar(30),
#option3 varchar(30)
as
begin
insert into QuestionEntry(Question,Round_Name) values(#question,#round_name);
declare #quesion_id int
exec #quesion_id= select Question_ID from QuestionEntry;
insert into Answer(Question_ID,Answer,Option1,Option2,Option3) values(#quesion_id,#answer,#option1,#option2,#option3);
end
Here I want to retrieve the Question_ID from table QuestionEntry and use that Question_ID to another table Answer
But this didn't work.
So how can I use above way?
please help me
Instead of
insert into QuestionEntry(Question,Round_Name) values(#question,#round_name);
declare #quesion_id int
exec #quesion_id= select Question_ID from QuestionEntry;
use the following:
DECLARE #quesion_id int
INSERT INTO QuestionEntry(Question,Round_Name) values(#question,#round_name)
SET #quesion_id = SCOPE_IDENTITY()
You should not use "exec" there.
What exec does is:
Executes a command string or character
string within a Transact-SQL batch, or
one of the following modules: system
stored procedure, user-defined stored
procedure, scalar-valued user-defined
function, or extended stored
procedure.
You should use "set" or "select" instead of exec.
SET can only assign one variable at
a time, SELECT can make multiple
assignments at once. When assigning
from a query if there is no value
returned then SET will assign
NULL, where SELECT will not make
the assignment at all (so the variable
will not be changed from it's previous
value)
You can find more info about when to use SET or SELECT here: SET vs SELECT when assigning variables
Sample:
set #quesion_id = (select Question_ID from QuestionEntry)
select #quesion_id = (select Question_ID from QuestionEntry)
But that's also wrong way to get identity value from inserted record. If you have N users execute a same procedure at a same time it can happen that you will get wrong value (from last inserted record).
To do this properly you should use ##IDENTITY or even better SCOPE_IDENTITY(). More info: here.
After INSERT you can simply call:
SELECT #quesion_id = ##IDENTITY
--or
SELECT #quesion_id = SCOPE_IDENTITY()
Also, check your Question_ID is configured properly. It should be set to auto increment.
Sample:
Question_ID int IDENTITY(1,1)PRIMARY KEY CLUSTERED
The 1's following the IDENTITY keyword indicate the SEED number (value for first record in table) and increment property (0 or 1).
If your server's version is SQL Server 2005 or higher, you could also try something like this:
create procedure InsertQuestionEntry
#round_name varchar(40),
#question varchar(100),
#answer varchar(40),
#option1 varchar(20),
#option2 varchar(30),
#option3 varchar(30)
as
begin
insert into QuestionEntry(Question,Round_Name)
output inserted.Question_ID, #answer, #option1, #option2, #option3
into Answer (Question_ID, Answer, Option1, Option2, Option3)
values(#question,#round_name);
end