Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

Friday, March 30, 2012

Return datetime type variable from SP

How can I return a datetime type variable from a stored procedure in SQL Server to C# code?

Hello,

I don't know if I got it right, but to return anything from a Stored procedure just make something like:

Select client_datecreated from clients

if you need a date put it as a field then in C# execute the command and use the sqldatareader class:

check msdnhere

The command can be a Stored as well as a query.

|||Do i need to set an output parameter in the SP? The syntax in the SP is confusing me.|||

select convert(char(10),fieldname in table,101) as test_Date from tablename

the 101 is a code which gives the date in mm/dd/yyyy format.

You should check with 'books online" in your SQL server help section.that gives you a list of different format you may want your date to be in.

convert basicly is truncating your date to have 10 characters otherwise you will have the hours:minute:seconds too in your result.

|||

If you would like to get data as return parameter (not return Value which is always int) you have to define it as OUTPUT in stored procedure definition, and also you have to setup this parameter as output in your SQLcommand object parameters definition.

If you would like to return it as cell in result table you do not have to define parameter and you can just do select yourdatafied from yourtable at the end of your stored procedure.

But SQL Command with output parameter is more elegant solution and will work a little faster ( .net do not have to create table structure for returned data)
and you can use executeNonQuery instead of execute scalar or execute reader.

See VB or C# help for syntax how to do this if you will have problems post again, but help is very good in VS so you should be good.

Friday, March 23, 2012

Retrieving XML Data using FOR XML AUTO into sql variable

hello guru's

I am using SQL server 2000, Version 8.0(SP4)
I need to put XML string returned from SELECT FOR XML AUTO query to a variable, But i can not able to do it in Transact SQL . can you please help me out ?

Declare @.Message varchar(200)

SELECT col1,col2 from table1 FOR XML AUTO

I need to put result of above query to @.Message variable.

I have tried with following but failed ......

SET @.Message = SELECT col1,col2 from table1 FOR XML AUTO

SET @.Message = sp_executesql N'SELECT col1,col2 from table1 FOR XML AUTO'

can anyone suggest me the solution to this .....

Thanks

Which version of SQL Server are you using -- 2000 or 2005?

|||

Parentheses should help e.g.

Code Snippet

SET @.Message = (SELECT col1, col2 FROM table1 FOR XML AUTO);

|||Thanks Kent for pointing me out,

I am using SQL server 2000 Version 8.0(SP4)

I have updated the post.

Thanks

|||Hello Martin,

Parenthesis does not helped ...It is giving syntax error.

Thanks for reply
|||

Sorry, works with SQL Server 2005 I tested with but then obviously not with SQL Server 2000 which you are using.

|||

Hi,

The code you are trying to execute will not work as FOR XML is not supported to work with assignment in SQL Server 2000. This works only with 2005

Retrieving XML Data using FOR XML AUTO into sql variable

hello guru's

I am using SQL server 2000, Version 8.0(SP4)
I need to put XML string returned from SELECT FOR XML AUTO query to a variable, But i can not able to do it in Transact SQL . can you please help me out ?

Declare @.Message varchar(200)

SELECT col1,col2 from table1 FOR XML AUTO

I need to put result of above query to @.Message variable.

I have tried with following but failed ......

SET @.Message = SELECT col1,col2 from table1 FOR XML AUTO

SET @.Message = sp_executesql N'SELECT col1,col2 from table1 FOR XML AUTO'

can anyone suggest me the solution to this .....

Thanks

Which version of SQL Server are you using -- 2000 or 2005?

|||

Parentheses should help e.g.

Code Snippet

SET @.Message = (SELECT col1, col2 FROM table1 FOR XML AUTO);

|||Thanks Kent for pointing me out,

I am using SQL server 2000 Version 8.0(SP4)

I have updated the post.

Thanks

|||Hello Martin,

Parenthesis does not helped ...It is giving syntax error.

Thanks for reply
|||

Sorry, works with SQL Server 2005 I tested with but then obviously not with SQL Server 2000 which you are using.

|||

Hi,

The code you are trying to execute will not work as FOR XML is not supported to work with assignment in SQL Server 2000. This works only with 2005

Retrieving the name of a job while it is executing

Does anyone know of a way to get the name of the job that is running. Is
there a variable that this is stored in similar to @.@.servername or a stored
procedure that can return this information. I am wanting to capture the
jobname while the job is running
Thanks,
Randy Bunton
One method is to specify a '[JOBID]' token in your job step T-SQL script.
You can then use this value to retrieve the job name from sysjobs. For
example.
SELECT name
FROM msdb..sysjobs
WHERE job_id = CAST([JOBID] AS uniqueidentifier)
Note that SQL Server Agent job tokens can only be specified in the directly
executed script. If you need the value in stored procedures, etc, you can
pass the value as a parameter.
Hope this helps.
Dan Guzman
SQL Server MVP
"Randy Bunton" <buntonrl@.charlestoncpw.com> wrote in message
news:uVYnPsiSEHA.3988@.tk2msftngp13.phx.gbl...
> Does anyone know of a way to get the name of the job that is running. Is
> there a variable that this is stored in similar to @.@.servername or a
stored
> procedure that can return this information. I am wanting to capture the
> jobname while the job is running
> Thanks,
> Randy Bunton
>

Retrieving the name of a job while it is executing

Does anyone know of a way to get the name of the job that is running. Is
there a variable that this is stored in similar to @.@.servername or a stored
procedure that can return this information. I am wanting to capture the
jobname while the job is running
Thanks,
Randy BuntonOne method is to specify a '[JOBID]' token in your job step T-SQL script
.
You can then use this value to retrieve the job name from sysjobs. For
example.
SELECT name
FROM msdb..sysjobs
WHERE job_id = CAST([JOBID] AS uniqueidentifier)
Note that SQL Server Agent job tokens can only be specified in the directly
executed script. If you need the value in stored procedures, etc, you can
pass the value as a parameter.
Hope this helps.
Dan Guzman
SQL Server MVP
"Randy Bunton" <buntonrl@.charlestoncpw.com> wrote in message
news:uVYnPsiSEHA.3988@.tk2msftngp13.phx.gbl...
> Does anyone know of a way to get the name of the job that is running. Is
> there a variable that this is stored in similar to @.@.servername or a
stored
> procedure that can return this information. I am wanting to capture the
> jobname while the job is running
> Thanks,
> Randy Bunton
>

Retrieving the name of a job while it is executing

Does anyone know of a way to get the name of the job that is running. Is
there a variable that this is stored in similar to @.@.servername or a stored
procedure that can return this information. I am wanting to capture the
jobname while the job is running
Thanks,
Randy BuntonOne method is to specify a '[JOBID]' token in your job step T-SQL script.
You can then use this value to retrieve the job name from sysjobs. For
example.
SELECT name
FROM msdb..sysjobs
WHERE job_id = CAST([JOBID] AS uniqueidentifier)
Note that SQL Server Agent job tokens can only be specified in the directly
executed script. If you need the value in stored procedures, etc, you can
pass the value as a parameter.
Hope this helps.
Dan Guzman
SQL Server MVP
"Randy Bunton" <buntonrl@.charlestoncpw.com> wrote in message
news:uVYnPsiSEHA.3988@.tk2msftngp13.phx.gbl...
> Does anyone know of a way to get the name of the job that is running. Is
> there a variable that this is stored in similar to @.@.servername or a
stored
> procedure that can return this information. I am wanting to capture the
> jobname while the job is running
> Thanks,
> Randy Bunton
>

Wednesday, March 21, 2012

Retrieving Scope_Entity or Identity from an SQL Insert

The following code inserts a record into a table. I now wish to retrieve the IDENTITY of that entry into a variable so that I can use it again as input for other inserts. Can someone offer assistance in handling this... I tried several alternatives that I found on the internet but none seem to work...

Thanks!

Dim objConn3As SqlConnection
Dim mySettings3AsNew NameValueCollection
mySettings3 = AppSettings
Dim strConn3AsString
strConn3 = mySettings3("connString")
objConn3 =New SqlConnection(strConn3)
Dim strInsertPatientAsString
Dim cmdInsertAs SqlCommand
Dim strddlSexAsString
Dim strddlPatientStateAsString
Dim rowsAffectedAsInteger

strddlSex = ddlSex.SelectedItem.Text
strddlPatientState = ddlPatientState.SelectedItem.Text

strInsertPatient ="Insert ClinicalPatient ( UserID, Accession, FirstName, MI, " & _
"LastName, MedRecord, ddlSex, DOB, Address1, Address2, City, Suite, strddlPatientState, " & _
"ZIP, HomeTelephone, OutsideNYC, ClinicalImpression, Today_Date_Month, Today_Date_Day, " & _
"Today_Date_Year) Values (@.UserID, @.Accession, @.FirstName, @.MI, @.LastName, @.MedRecord, " & _
"'" & strddlSex &"', @.DOB, @.Address1, @.Address2, @.City, @.Suite , '" & strddlPatientState &"', " & _
"@.ZIP, @.HomeTelephone, @.OutsideNYC, @.ClinicalImpression, @.Today_Date_Month, @.Today_Date_Day, " & _
"@.Today_Date_Year)SELECT @.@.IDENTITY AS NewID SET NOCOUNT OFF"

cmdInsert =New SqlCommand(strInsertPatient, objConn3)

cmdInsert.Parameters.Add("@.UserID","Joe For Now")
cmdInsert.Parameters.Add("@.Accession", Accession.Text)
cmdInsert.Parameters.Add("@.LastName", LastName.Text)
cmdInsert.Parameters.Add("@.MI", MI.Text)
cmdInsert.Parameters.Add("@.FirstName", FirstName.Text)
cmdInsert.Parameters.Add("@.MedRecord", MedRecord.Text)
cmdInsert.Parameters.Add("@.ddlSex", strddlSex)
cmdInsert.Parameters.Add("@.DOB", DOB.Text)
cmdInsert.Parameters.Add("@.Address1", Address1.Text)
cmdInsert.Parameters.Add("@.Address2", Address2.Text)
cmdInsert.Parameters.Add("@.City", City.Text)
cmdInsert.Parameters.Add("@.Suite", Suite.Text)
cmdInsert.Parameters.Add("@.strddlPatientState", strddlPatientState)
cmdInsert.Parameters.Add("@.ZIP", zip.Text)
cmdInsert.Parameters.Add("@.HomeTelephone", Phone.Text)
cmdInsert.Parameters.Add("@.OutsideNYC", OutsideNYC.Text)
cmdInsert.Parameters.Add("@.ClinicalImpression", ClinicalImpression.Text)
cmdInsert.Parameters.Add("@.Today_Date_Month", Today_Date_Month.Text)
cmdInsert.Parameters.Add("@.Today_Date_Day", Today_Date_Day.Text)
cmdInsert.Parameters.Add("@.Today_Date_Year", Today_Date_Year.Text)

objConn3.Open()
cmdInsert.ExecuteNonQuery()
objConn3.Close()

Try this - a zillion ways to get Scope_Identity back:http://www.mikesdotnetting.com/Article.aspx?ArticleID=54

Friday, March 9, 2012

Retrieving a Value from a SQL Database in Code Behind

VWD 2005 Express. I need to retrieve a value from a SQL database from the code behind a page and assign it to a variable. In Microsoft Access I can do this using the DLookup function. What I need to do is get the data that results from the following query into a variable:

SELECT [SystemUserId] FROM [SystemUser] WHERE ([Username] = @.Username)

The name of the data source is SqlDataSource2

Also, in Access I can create a recordset from a query and then process through the recordset. Can that be done in VB code in VWD 2005 Express?

I wouldn't use a SqlDataSource for this. I would use ADO.NET code and ExecuteScalar to obtain one value.

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Their are two potential equivalents to a RecordSet. One is using a DataReader, for forward only, read only access, and the other is a DataSet, in which you can move forwards and backwards. DataReader is the more common approach, but it depends on what you want to do.

http://msdn2.microsoft.com/EN-US/library/system.data.sqlclient.sqldatareader.aspx

|||

Thanks Mike. I looked at the link. The MSDN info is so cryptic to me that I cannot discern what to do. Could you provide a real VB code example of what you are talking about? Thanks for the help.

|||

Dim SystemUserId As Int32 = 0
Dim sql As String = "SELECT [SystemUserId] FROM [SystemUser] WHERE ([Username] = @.Username)"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@.UserName", TxtUserName.Text)
Try
conn.Open()
SystemUserId = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
'Do whatever with Exceptions
End Try
End Using

In the line that starts cmd.Parameters.AddWithValue, I have assumed that the value for the @.Username will come from a TextBox called TxtUserName. Of course, you would need to adjust this to reflect the actual source. Also, connString is a variable of type String that contains your connection string. You would obviously have to suuply this value as well.

|||

Mike. I tried the following using a code example from the link you provided. I get errors saying that types SqlConnection and SqlCommand are not defined. What do I need to do here? Thanks.

ProtectedFunction GetSystemUserId(ByVal UsernameAsString)AsString

Dim connStringAsString ="<%$ ConnectionStrings:GoodNews_IntranetConnectionString %>"

Dim UserIDAsString

Dim sqlAsString ="SELECT [SystemUserId] FROM [SystemUser] WHERE ([Username] = '" + Username +"')"

Using connAsNew SqlConnection(connString)

Dim cmdAsNew SqlCommand(sql, conn)

Try

conn.Open()

UserID = Str(cmd.ExecuteScalar())

Catch exAs Exception

Console.WriteLine(ex.Message)

EndTry

EndUsing

Return UserID

EndFunction

|||

You need to add

Imports System.Data.SqlClient

at the top of the page. That makes the classes relating to connections and commands within the System.Data.SqlClient available to that page. The alternative is to use the full reference:

Using conn as new System.Data.SqlClient.SqlConnection

etc. Imports statements save a lot of typing in the long run.

|||

Thanks loads Mike!!! After I added the "Imports" at the top, all I had to do was modify my connection string (just copied from my web.config file) and she worked. You have now moved me from novice level 1 to novice level 1.1. Thanks and God bless.

|||

Novice level 1.1's will use:

Dim Conn as new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString)

and keep the connection string in the connection string section of the web.config file.

|||

I would be interested on the information on what you called "DataSet." Can you provide a link?

|||

Public Function GetDataSet(ByVal SQLString As String) As DataSet
Dim cmd As New SqlCommand(SQLString)
Return GetDataSet(cmd)
End Function

Public Function GetDataSet(ByVal cmd As SqlCommand) As DataSet
NullifyParameters(cmd)
Dim DS As New DataSet
Dim MyCommand As SqlDataAdapter
OpenConn(cmd)
cmd.CommandTimeout = m_CommandTimeout
MyCommand = New SqlDataAdapter(cmd)
'MyCommand.SelectCommand.CommandTimeout = m_CommandTimeout -- Change if you want
MyCommand.Fill(DS, "DS")
CloseConn(cmd)
Return DS
End Function

Private Sub NullifyParameters(ByVal cmd As SqlCommand)
For Each p As SqlParameter In cmd.Parameters
If p.Value Is Nothing OrElse (TypeOf p.Value Is String AndAlso p.Value.Length = 0 AndAlso (p.SqlDbType = SqlDbType.DateTime OrElse p.SqlDbType = SqlDbType.Int OrElse p.SqlDbType = SqlDbType.Money OrElse p.SqlDbType = SqlDbType.Real OrElse p.SqlDbType = SqlDbType.Float OrElse p.SqlDbType = SqlDbType.Decimal OrElse p.SqlDbType = SqlDbType.BigInt OrElse p.SqlDbType = SqlDbType.UniqueIdentifier OrElse p.SqlDbType = SqlDbType.TinyInt)) Then
p.Value = DBNull.Value
End If
Next
End Sub

I can't really provide the OpenConn/CloseConn functions, but they do what you would expect them to basically. They just have transaction support in them, which then needs more functions, etc. So here are some ones that will do what you want:

Private OpenConn(cmd as SqlCommand)

dim conn as new SqlConnection(System.Configuration.ConfigurationManager("ConnectionString").ToString)

conn.open

cmd.Connection=conn

end Sub

Private CloseConn(cmd as SqlCommand)

cmd.Connection.Close

end sub

|||

Add those functions to any code file you want to use them in (or make them part of a class library), and then you can do things like:

Dim MyDataSet as dataset = GetDataSet("SELECT * FROM MyTable")

then you can iterate through the dataset rows like

For each dr as datarow in MyDataSet.tables(0).Rows

if dr("Column1")= ... then

' Do something here

end if

next

|||

I placed your code in a class module. I got the following errors. Any help in clearing these up would be appreciated. Thanks.

The following code generates the error, "Type 'DataSet not defined."

PublicFunction GetDataSet(ByVal SQLStringAsString)As DataSet

Dim cmdAsNew SqlCommand(SQLString)

Return GetDataSet(cmd)

EndFunction

The following code generates the error, "m_CommandTimeout not declared."

PublicFunction GetDataSet(ByVal cmdAs SqlCommand)As DataSet

NullifyParameters(cmd)

Dim DSAsNew DataSet

Dim MyCommandAs SqlDataAdapter

OpenConn(cmd)

cmd.CommandTimeout = m_CommandTimeout

MyCommand =New SqlDataAdapter(cmd)

'MyCommand.SelectCommand.CommandTimeout = m_CommandTimeout -- Change if you want

MyCommand.Fill(DS,"DS")

CloseConn(cmd)

Return DS

EndFunction

The following code generates the error, "SqlDbType is not declared."

PrivateSub NullifyParameters(ByVal cmdAs SqlCommand)

ForEach pAs SqlParameterIn cmd.Parameters

If p.ValueIsNothingOrElse (TypeOf p.ValueIsStringAndAlso p.Value.Length = 0AndAlso (p.SqlDbType = SqlDbType.DateTimeOrElse p.SqlDbType = SqlDbType.IntOrElse p.SqlDbType = SqlDbType.MoneyOrElse p.SqlDbType = SqlDbType.RealOrElse p.SqlDbType = SqlDbType.FloatOrElse p.SqlDbType = SqlDbType.DecimalOrElse p.SqlDbType = SqlDbType.BigIntOrElse p.SqlDbType = SqlDbType.UniqueIdentifierOrElse p.SqlDbType = SqlDbType.TinyInt))Then

p.Value = DBNull.Value

EndIf

Next

EndSub

The following code generates the error, "Error 14 'ConfigurationManager' is a type in 'Configuration' and cannot be used as an expression."

Dim connAsNew SqlConnection(System.Configuration.ConfigurationManager("ConnectionString").ToString)

|||

Add

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration

to the top of the file containing these methods.

Comment out the Timout line. The default value is good for most scenarios. You will know if you have to increase it, because you get Timeout errors.


|||

The changes that mike suggested should fix the errors. If they don't, please post again.

|||

Mike:

I put the routines you gave me into a class module and I defined them as Shared so that I may call them from other modules. However, when I change the code as shown below (adding the Shared) I get the error that follows. Also I am confused as to how you can have two routines called "GetDataSet." How does the code know which one you are calling?

Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.

Public SharedFunction GetDataSet(ByVal SQLStringAsString)As DataSet

Dim cmdAsNew SqlCommand(SQLString)

Return GetDataSet(cmd)

EndFunction

PrivateFunction GetDataSet(ByVal cmdAs SqlCommand)As DataSet

NullifyParameters(cmd)

Dim DSAsNew DataSet

Dim MyCommandAs SqlDataAdapter

OpenConn(cmd)

'cmd.CommandTimeout = m_CommandTimeout

MyCommand =New SqlDataAdapter(cmd)

'MyCommand.SelectCommand.CommandTimeout = m_CommandTimeout -- Change if you want

MyCommand.Fill(DS,"DS")

CloseConn(cmd)

Return DS

EndFunction

Wednesday, March 7, 2012

retrieve stored procedure

I need some help retrieving the stored procedure listed below. I would like to use a drop list to select the variable "UserName" and textboxes to send the variables "StartingDate" and "EndingDate". How do I pass these variables and then have the results show up in a gridview? Any advice would be greatly appreciated.

CREATE PROCEDURE [dbo].[aspnet_starterkits_GetTimeEntryUserReportByUserNameAndDates]
@.UserName NVARCHAR(256),
@.StartingDate datetime,
@.EndDate datetime
AS
DECLARE @.UserId AS UNIQUEIDENTIFIER
SET NOCOUNT ON

SELECT @.UserId=UserId FROM aspnet_users WHERE UserName=@.UserName

SELECT
@.UserName as UserName,
SUM (timeentryDuration) AS TotalDuration,
SUM (timeentryOvertime) AS TotalOvertimeHours
FROM
aspnet_starterkits_TimeEntry
WHERE
aspnet_starterkits_TimeEntry.TimeEntryUserId=@.UserId
AND
TimeEntryDate between @.StartingDate and @.EndDate

Hello,

Here is a working sample. Hope it can help.

<%@. Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
protected void Button1_Click(object sender, EventArgs e)
{

GridView1.Visible = true;

}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
</td>
<td> <asp:DropDownList ID="ddl1" runat="server" DataSourceID="SqlDataSource2"
DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList><asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:aspnet_staterKits_TimeTracker%>"
SelectCommand="SELECT [UserName] FROM [vw_aspnet_Users]"></asp:SqlDataSource>

</td>
<td>
</td>
</tr>
<tr>
<td>T1
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>T2
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
<td>
</td>
</tr>
</table>
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Visible="false"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="TotalDuration" HeaderText="TotalDuration" SortExpression="TotalDuration" />
<asp:BoundField DataField="TotalOvertimeHours" HeaderText="TotalOvertimeHours" SortExpression="TotalOvertimeHours" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aspnet_staterKits_TimeTracker %>"
SelectCommand="aspnet_starterkits_GetTimeEntryUserReportByUserNameAndDates2" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Name="UserName" ControlID="ddl1" />
<asp:ControlParameter Name="StartingDate" ControlID="TextBox1"/>
<asp:ControlParameter Name="EndDate" ControlID="TextBox2"/>
</SelectParameters>
</asp:SqlDataSource>

</div>
</form>
</body>
</html>

Retrieve package varialbe from SQL configuration table?

Hi,

I have been trying to get a variable in my package to retrieve its data from the SQL configuration table.. so that in future i am able to alter them all easily.

On the SSIS > Package Configurations menu, there seems to only be the option to pass a variable FROM the package TO SQL

whereas what i want to do is infact the opposite...

any help would be much appreciated

regards

Chris

You were on the right track, you just second-guessed yourself.

On SSIS > Package Configurations menu set the following...

-Configuration type: 'SQL Server'

-Connection: 'Name of you SQL Server connection manager'

-Configuration table: 'Name of your SQL Server configuration table'

-Configuration filter: 'The name of the field that identifies the variable(s) you want to bring in to ssis'

This will not pass variables from SSIS to SQL Server but from the way you want it to, SQL Server to SSIS

|||Hi,

cheers for that, it turns out that it was wokring fine all the time!

I was expecting the variables to get updated when the package ran, but instead they seemt o get updated when the package is opened..

very odd

how does this affect the variables when the packages are run from outside of SSIS, i.e. scheduled in SQL Server?

Thanks!
|||

However the package is executed, it will always pull from that SQL Server config table to get the most current information.

So whether you execute the package in BIDS, or from a command line, or from SQL Server Agent, each will poll the table for current information each time. As you've found out, it also polls the table every time you open that package.

|||

Configurations are checked/updated on many occasions:

-Upon first opening up the package.

-In BIDS when you right-click on a package in the solution explorer and click 'reload with upgrade'.

-Run-time. Regardless of how it is executed (sql server agent, dtexec,BIDS).

Saturday, February 25, 2012

Retrieve ID of Last Insert (Scope_Identity)

(Newbie) Hi, I am trying to create in a session variable, the ID of the last inserted record. My reading suggests I should use Scope_Identity. I'm having trouble with the syntax/code structure. Also, is it good programming practise to directly assign the session variable e.g. "Session[var]=SqlDataSource.Select()"? The error I'm getting from my code below is "No overload for method SELECT takes 0 arguments". Thanks.

Session["snCoDeptRowID"] = SqlDataSource1.Select();

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT Scope_Identity"

</asp:SqlDataSource>

try

SelectCommand="SELECT Scope_Identity()"

|||

Thank you for the suggestion. Now I am having trouble with the following line of code which assigns the Scope_Identity() to a session variable. The error msg is: does not recognise the word "command". How can I get the value of the @.CoDeptRowID (Scope_Identity) into my session variable? Thanks

Session["snCoDeptRowID"] = Convert.ToInt32(e.command.parameters("@.CoDeptRowID").value);

|||

Check thate argument has a command object

only if its there in event argument you will be able to use it. And Check the Direction of the @.CoDeptRowId is set to Output in Command as well

|||

Hi,

There are many ways to get the SCOPE_IDENTITY() from stored procedure.

You can use SELECT SCOPE_IDENTITY() or RETURN SCOPE_IDENTITY() or SET @.PARAM = SCOPE_IDENTITY(). All is fine, but the way to get it is different.

SELECT will return the SCOPE_IDENTITY() as the first col and first row of a result set. RETURN will return is as a return parameter. While SET will set the value to a parameter and you have to specify it as an OUTPUT parameter when declaring it.

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!