|
Hello,
I'm having problems retrieving the values of a stored procedure's output parameters. I don't know if the problem is in the stored procedure or in the code.
When the procedure is executed, the records in the three tables are inserted correctly, and the identity from the first table is stored correctly in the other two tables.
When I try to get the value of the parameter after the ExecuteNonQuery call, an InvalidCastException exception is thrown. This is my code:
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = trans;
cmd.CommandText = "ReprDist_InsertDistributor";
cmd.Parameters.Add("@ID_representante", data.RepID);
cmd.Parameters.Add("@NombreComercial", (string) row["NombreComercial"]);
cmd.Parameters.Add("@Password", (string) row["Password"]);
SqlParameter paramDistID = cmd.Parameters.Add("@ID_distribuidor", SqlDbType.Int);
paramDistID.Direction = ParameterDirection.Output;
SqlParameter paramCompID = cmd.Parameters.Add("@ID_empresa", SqlDbType.Int);
paramCompID.Direction = ParameterDirection.Output;
SqlParameter paramUserID = cmd.Parameters.Add("@ID_usuario", SqlDbType.Int);
paramUserID.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
data.DistID = (int) paramDistID.Value;
data.CompanyID = (int) paramCompID.Value;
data.UserID = (int) paramUserID.Value; and this is my stored procedure:
ALTER PROCEDURE ReprDist_InsertDistributor
(
@ID_representante int,
@NombreComercial varchar(70),
@Password varchar(20),
@ID_distribuidor int OUTPUT,
@ID_empresa int OUTPUT,
@ID_usuario int OUTPUT
)
AS
INSERT INTO Empresas (NombreComercial, Direccion, Ciudad, Estado, Telefono, DireccionWeb, EMail, RazonSocial, DireccionFiscal, RFC)
VALUES (@NombreComercial, @Direccion, @Ciudad, @Estado, @Telefono, @DireccionWeb, @EMail, @RazonSocial, @DireccionFiscal, @RFC);
SELECT @ID_empresa = @@IDENTITY;
INSERT INTO Distribuidores (ID_empresa, ID_representante) VALUES (@ID_empresa, @ID_representante);
SELECT @ID_distribuidor = @@IDENTITY;
INSERT INTO Usuarios (Nombre, Apellido, Telefono, EMail, NombreUsuario, Password, ID_empresa)
VALUES (@Nombre, @Apellido, @TelefonoContacto, @EMailContacto, @NombreUsuario, @Password, @ID_empresa);
SELECT @ID_usuario = @@IDENTITY;
RETURN; If anyone can help me out, I'd appreciate it very much!
Thanks!
-- LuisR
Luis Alonso Ramos
Intelectix - Chihuahua, Mexico
Not much here: My CP Blog!
|
|
|
|
|
It suddenly started working, I don't know why!
-- LuisR
Luis Alonso Ramos
Intelectix - Chihuahua, Mexico
Not much here: My CP Blog!
|
|
|
|
|
|
I'm getting the following error "could not use '|';file already in use". From MSDN i got to know that this occurs if a db is tried to open when its already opened in exclusive mode. But it is not the case here. DB used in MS Access 97 and Dev Env is VC++ 6. Any help would be greatly appreciated.
Thanks
Vikram Attiganal
|
|
|
|
|
I'm currently using a StringBuilder in .NET to build a SQL Query and then using the SqlCommand object to append parameters. I'd like to move this into a stored procedure but am unsure how to do this as I have multiple WHERE clauses that depend on the condition of the form when the user submits it. I've been using sprocs for years now so 'how to create one' is not the issue. Whether and how to implement is where I'm trying to go with this question. The box is running SQL2K and I've read the performance gains that used to be realized for SQL7 have really gone away with optimizations and caching in 2K.
IE:
code looks something like below
VB Code in all caps
select ... from table where
IF FORM_CONDITION_1 THEN
append something to where clause
END IF
IF FORM_CONDITION_2 THEN
append something to where clause
END IF
IF FORM_CONDITION_3 THEN
append something to where clause
END IF
...
EXECUTE SQL COMMAND
I have 5 or 6 conditions that I'm checking for so writing a procedure for each possible set of circumstances seems somewhat silly. My recordsets coming back aren't really that large (50-120K of data on average) so I'm wondering the following.
1. Is there an easy way to perform conditional WHERE clauses in a T-SQL stored procedure without actually building the query in the procedure like I'm doing with the StringBuilder?
2. Should I just scrap the WHERE clause, return all the records and then use the RowFilter property of the datatable to filter my results before rendering them to the page?
3. Should I just continue using the StringBuilder method?
Any thoughts on how other people have handled a situations like this are appreciated.
Thanks,
-Brian
|
|
|
|
|
AnotherUser wrote:
Is there an easy way to perform conditional WHERE clauses in a T-SQL stored procedure without actually building the query in the procedure like I'm doing with the StringBuilder?
Yes.
AnotherUser wrote:
2. Should I just scrap the WHERE clause, return all the records and then use the RowFilter property of the datatable to filter my results before rendering them to the page?
No.
AnotherUser wrote:
3. Should I just continue using the StringBuilder method?
No way!
SELECT *
FROM SomeTable
WHERE (ConditionOne AND (OptionalSqlForConditionOne))
AND (ConditionTwo AND (OptionalSqlForConditionTwo))
AND....
Replace the bold-italic text with the necessary code. e.g. If, say, you are optionally testing whether the filter should be on a start date, you could supply a NULL value or the start date, so the condition would be @StartDate IS NOT NULL (Remember the condition must evaluate to true in order to process your Optional SQL.
For a fuller example, let's say you have two conditions, a start and end date.
SELECT * FROM MyTable
WHERE (@StartDate IS NOT NULL AND (StartDateColumn >= @StartDate))
AND (@EndDate IS NOT NULL AND (EndDateColumn <= @EndDate))
The additional brackets are not required round the Optional SQL IF the optional SQL is just one clause, or if all the clauses are joined together with an AND operator. You do need the surrounding brackets if you have OR clauses, or if your optional SQL needs brackets for other reasons.
Does this help?
Do you want to know more?
|
|
|
|
|
Colin,
Much appreciated. Yes, the example is perfect. I have a bunch of clauses but it's very workable.
Thanks again,
-Brian
|
|
|
|
|
Hey Colin,
I worked up the example and it doesn't really work as expected. Don't know if this is a SQL2K thing or just the way SQL works. The sample code below uses the pubs database.
declare @state char(2)
select @state = 'CA'
declare @au_lname varchar(40)
select @au_lname = 'G'
select * from dbo.authors
where (@state IS NOT NULL AND (state = @state))
and (@au_lname IS NOT NULL AND (au_lname LIKE @au_lname + '%'))
Running the statement as is returns some records. However, if either @state or @au_lname or both are null then no records are returned.
What I'm looking for is the opposite of this. if @state or @au_lname are null then the clause is ignored. If both are null than all records are returned.
-brian
|
|
|
|
|
I am really sorry - This is what I get for posting stuff staight out of my head without testing it first. I should really know better.
Anyway, the correct form using your example (which I have just tested) is:
select * from dbo.authors
where (@state IS NULL OR (state = @state))
and (@au_lname IS NULL OR (au_lname LIKE @au_lname + '%'))
Note that the IS NOT NULL is now IS NULL and the AND between the condition and the filter is now an OR
I hope this works out better for you.
Do you want to know more?
WDevs.com - The worlds first Developers Services Provider
|
|
|
|
|
Much better. Works as advertised.
Thanks,
-Brian
|
|
|
|
|
Made a few changes working on what you originally supplied and have something that works. If the parameter is null then I have '1=1' added to it evaluates true for each row checked. If it isn't null then it performs the requested check.
Thanks again for the idea.
-Brian
declare @state char(2)
select @state = 'TN'
declare @au_lname varchar(40)
select @au_lname = 'G'
select * from dbo.authors
where ((@state IS NULL AND 1 = 1) OR (state = @state))
and ((@au_lname IS NULL AND 1 = 1) OR (au_lname LIKE @au_lname + '%'))
order by au_lname
|
|
|
|
|
I have a DTS that takes Visual FoxPro files (.dbf) and reads them to then transform the data and load it into SQL Server.
it runs quite well when executed manually. Fails every time when trying to
run it as a scheduled job via asp.net.
Step Error Source: Microsoft Data Transformation Services (DTS) Package
i have done a test as below:
If I add other tasks such as ActiveX tasks to delete some specific data from the tables in SQL Server,the "delete" task canbe executed quite well,but still failed when transforming the data.i think this test means the problem maybe from foxpro.
Is there any one who can help me? Thank you in advance!
|
|
|
|
|
I have a problem here while excecute a oledb datareader...
<br />
<br />
...<br />
<br />
rdr.close();
<br />
cmd.CommandText = "SELECT MID FROM MandantMC";<br />
<br />
rdr = cmd.ExecuteReader();<br />
<br />
if(rdr.HasRows)<br />
{<br />
strDir = rdr.GetString(0);
...
rdr has rows but responsed with this message:
System.InvalidOperationException: No data for row/column
I don't understand this. The SQL Query analyzer give me correct results, but not this app. Before I started the Excecution of this datareader, I have closed one before ( you can see the first code line ). First request works. After closing it, the second ( the new ExcecuteReader ) fails. Maybe "cmd" make problems ?
|
|
|
|
|
After the ExecuteReader() do a rdr.Read().. it will fix your problem. First record does not get read automatically.
|
|
|
|
|
Hi, I have a Decimal(9,2) type, and I want to evaluate the fractional component of this. What I actually want to know is if there is a sql function to perform this. If I had 13.45, is there a function to return .45?
|
|
|
|
|
The following should get you what you want:
SELECT (MyDecimalColumn - CAST(MyDecimalColumn AS INT)) AS MyFractionalComponent
FROM ....
Do you want to know more?
|
|
|
|
|
I know that ADO doesnt like binary blobs of paradox tables.
i wonder if anyone knows a way to work around this
i was thinking about using Borland C++ to build a library (dll ) and then use it in C#.. but it is a lito more than i can handle rightnow..
any suggestion would be great..thank you
Elapid For The Win
|
|
|
|
|
How can i update my DataSourc(SQL SERVER) from an DataSet
Thank you
|
|
|
|
|
|
Hello,
I have three tables: Distributors, Business, Users. The Distributors table only has three fields: ID_distributor, an ID_Business, and an ID_repr (like the boss of that distributor). The Business table has information about the business (Name, Address and so on) and the User table about people accesing the web site (login name, password, and the ID_business they belong to.)
So, I want to insert a new Distributor from a web page. I need to first add a new Business record, and then (in any order) the Distributor record and the User record. (EDIT: Obviously, I want to store the first record's ID in the other two tables, to keep the relation. @@IDENTITY would help here, wouldn't it?))
And finally, I need it to return all the three IDs (distributor, business and user).
I've never written a stored procedure by hand (only designed them with Access) so I have no idea of the syntax. There are many more fields, but I'd like just to see the general structure of that stored procedure and how to use output parameters and so on.
Thanks in advance,
-- LuisR
Luis Alonso Ramos
Intelectix - Chihuahua, Mexico
Not much here: My CP Blog!
|
|
|
|
|
Believe it or not, it is basically similar to writing a VB function with some VB and SQL code inside.
You declare the procedure name and the parameters to be passed (or returned as output), and write your code inside. Below is the basic structure of it:
CREATE PROC[EDURE] procedure_name [;number]
[
{@parameter data_type} [VARYING] [= default] [OUTPUT]
]
[,...n]
AS
(code starts here)
Here is a link that has some good examples of stored procedure. I believe you can start writing your own after reading it.
Creating Stored Procedure[^]
Edbert P.
Sydney, Australia.
|
|
|
|
|
Thanks! I'll take a look at it! With a few examples, what I want to do may not be that hard.
-- LuisR
Luis Alonso Ramos
Intelectix - Chihuahua, Mexico
Not much here: My CP Blog!
|
|
|
|
|
I have the following section of code
str_SQL = "(SELECT Description.DescKey " _
& "FROM (Category INNER JOIN SubCategory ON Category.CategoryKey = SubCategory.CategoryKey) " _
& "INNER JOIN Description ON SubCategory.SubCategoryKey = Description.SubCategoryKey " _
& "WHERE (Category.CategoryDescription)='" & GetCurrCategory & "')"
'TO REMOVE
CurrentDb.QueryDefs.Delete "qdf_q"
'Create sub query
Dim qdf_Query As QueryDef
Set qdf_Query = CurrentDb.CreateQueryDef("qdf_q", str_SQL)
DoCmd.OpenQuery ("qdf_q")
'Build base action
str_SQL = "DELETE FROM Description " _
& "WHERE DescKey " _
& "IN (qdf_q)"
'Execute Query
CurrentDb.Execute (str_SQL)
The queries with code format removed are:
SELECT Description.DescKey
FROM (Category INNER JOIN SubCategory ON Category.CategoryKey = SubCategory.CategoryKey)
INNER JOIN Description ON SubCategory.SubCategoryKey = Description.SubCategoryKey " _
WHERE (Category.CategoryDescription = GetCurrCategory())
DELETE FROM Description
WHERE DescKey
IN (qdf_q)
Now, the problem I have is, the first query generates the correct table, which contains all the items I want to remove. But when I try and run the second query, It displays an error saying "Too few parameters, expected 1"
I have all the single parameter covered already, so why is it doing this?
Cheers
Cata
(Sorry, SQL n00b )
|
|
|
|
|
Hi Cata. You're creating the select query as a temporary QueryDef object and referencing its name in your delete statement. When executing the delete statement with CurrentDb.Execute(str_SQL) , the name [qdf_q] is not recognized (its scope is as a variable in your procedure); thus, Access wants to treat it as a parameterized name (in the scope of the SQL), and without explicitly assigning a parameter object with that name to the QueryDef, you're getting the "Too few parameters" error.
I would think a way to avoid this is to build in the Select statement as part of the str_SQL string (not a QueryDef) then execute str_SQL with the subquery. The resulting SQL would look something like this:
DELETE FROM Description
WHERE DescKey
IN
(
SELECT Description.DescKey
FROM (Category INNER JOIN SubCategory
ON Category.CategoryKey = SubCategory.CategoryKey)
INNER JOIN Description
ON SubCategory.SubCategoryKey = Description.SubCategoryKey
WHERE (Category.CategoryDescription = GetCurrCategory())
) Does that make sense? The variable str_SQL would hold the complete text as above, then would be executed without creating a QueryDef object.
|
|
|
|
|
The qdf_Query is the procedural object, qdf_q is an actual database query that exists within the access DB. I can see it in the query viewer.
The qdf_q query is fully populated as well, so there is no reason why it should not work.
When I tried to integrate the sub query by using SQL, it threw and INNER JOIN Syntax error. The current solution displays "Too Few Parameters, Expected 1". But when i experimented with using a table, it worked fine.
This is confusing me. A table works, but a query that produces a far simpler table, requires additional input? Why is this?
Cheers
Cata
|
|
|
|
|