Output parameters for dynamic SQL

N

Nemisis

Hi everyone,

I am saving a record to SQL and want to return the ID of the record
added as an output parameter, can you do this in dynamic SQL, without
the use of a stored procedure??

i.e.

comm = new sqlcommand
comm.commandtext = "Insert (name) values (@name); select @id =
SCOPE_IDENTITY();

' add parameters to command etc

comm.executeNonQuery()

dim a as integer = ctype(comm.parameters.item("@id").value, integer)

Is this possible?? I know you can do it in SQL but we have over 80
databases that this data layer will connect to and i am not one for
duplicate code over each database, just encase one database had a
different version of the sproc for whatever reason.
 
D

Dblood

Nemisis,

Try this:

Dim oTestCon As SqlConnection
Dim oTestCmd As SqlCommand
Dim result As Int16

oTestCon = New SqlConnection("Data Source=XXXX;Initial Catalog=XXX;User
Id=XXX;Password=XXX;")
oTestCmd = New SqlCommand("INSERT INTO
(field) VALUES (value)
SELECT @@identity", oTestCon)

oTestCon.Open()
result = oTestCmd.ExecuteScalar()
oTestCon.Close()
Response.Write(result)

Should give you what you're looking for (result = newly added rec id).
Let me know if I misunderstood what you needed.

dkb
 
D

Dave Sexton

Hi,

Yes, you can add output parameters to queries:

Dim command As New SqlCommand("SELECT @ID = 55", conn)
command.Parameters.Add("@ID", System.Data.SqlDbType.Int)
command.Parameters.Items("@ID").Direction = System.Data.ParameterDirection.Output

command.ExecuteNonQuery()

Dim id As Integer = CType(command.Parameters.Items("@ID").Value, Integer);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top