Retrieve Guid After Inserting Recrod With NEWID()

Mar 3, 2007

Hi There,

I'm having a problem retreiving the auto generated Guid after inserting anew record with NEWID(), my stored proc is as follows:SET @uiTransactionID = NEWID()
INSERT INTO Transactions (uiTransactionID) VALUES (@uiTransactionID)
IF @@ERROR = 0 AND @@ROWCOUNT = 1
BEGIN
SELECT @uiTransactionID AS '@@GUID'
RETURN 0
END

 And the return on my insert statement is:

command.ExecuteNonQuery();
m_uiTransactionID = (Guid)command.Parameters["RETURN_VALUE"].Value;

I can never retreive the newly generated Guid, can onyone spot where i'm going wrong?

Many thanks

Ben

View 2 Replies


ADVERTISEMENT

How To Retrieve The GUID Value Of A SQL NewID() Identity Column After An Insert ?

Jan 10, 2006

Hello,

In my table, i've a GUID column type. I insert a new record with NewID() function in Sql request.

Is it possible to retreive the GUID column of this new record (without requerying the table) ?

I'm using EVC, Sql Mobile 3.0 and OLE DB interface.

Thanks in advance.

View 1 Replies View Related

Do I Need To Verify That NewID() Returns A Unique GUID?

Oct 26, 2007

 I'm migrating a web based system to SQL server.  I'm planning on using the SQL server function NewID() to create unique keys for many of my records in many different tables.  I'm just wondering if NewID() is guaranteed to return a value that does not already exist in my database.  I mean obviously once you have a certain number of records (a hell of a lot) you'd be breaking the odds to never come up with a duplicate. Do I need to make sure the result of NEWID() doesn't already exist?Thanks 

View 1 Replies View Related

Retrieve The GUID For Inserted Record

May 2, 2006

I am using this code to insert a record in my table where i have assigned a guid datatype field to generate an automatic guid for each record. but now i need to retrieve the guid to use it to send a confirmation email to the user.
 
SqlConnection sql_connection = new SqlConnection("Server=xxx.xxx.xx.xxx;uid=xxxxxxxx;password=xxxxxxx;database=xxxxxxx;");SqlCommand sql_command = new SqlCommand("INSERT INTO members (member_sex, member_cpr, member_nationality, member_block, member_gov, member_daaera, member_email, member_mobile, member_created_ip) Values (@member_sex, @member_cpr, @member_nationality, @member_block, @member_gov, @member_daaera, @member_email, @member_mobile, @member_created_ip)", sql_connection);
sql_command.Parameters.Add(new SqlParameter("@member_sex", Session["member_sex"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_cpr", Session["member_cpr"]));sql_command.Parameters.Add(new SqlParameter("@member_nationality", Session["member_nationality"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_block", Session["member_block"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_gov", "GOV"));sql_command.Parameters.Add(new SqlParameter("@member_daaera", 6));sql_command.Parameters.Add(new SqlParameter("@member_email", Session["member_email"].ToString().ToLower()));sql_command.Parameters.Add(new SqlParameter("@member_mobile", Session["member_mobile"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_created_ip", Request.UserHostAddress.ToString()));
sql_connection.Open();sql_command.ExecuteNonQuery();sql_connection.Close();
 

View 1 Replies View Related

Inserting Into A Table With Guid As Key

May 23, 2004

I am having a terrible time doing an insert.... dispite what the error message says, I think it has something to do with trying to insert a GUID (my primary key).... but I am probably wrong :-)

Any ideas


The error message


Server Error in '/LightQuote' Application.
--------------------------------------------------------------------------------

Prepared statement '(@User_ID uniqueidentifier,@User_Type int,@Status int,@UserName ' expects parameter @UserName, which was not supplied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Prepared statement '(@User_ID uniqueidentifier,@User_Type int,@Status int,@UserName ' expects parameter @UserName, which was not supplied.

Source Error:


Line 195: dbConnection.Open()
Line 196: Try
Line 197: rowsAffected = dbCommand.ExecuteNonQuery
Line 198: Finally
Line 199: dbConnection.Close()



The Insert Function

Public Function InsertOneUser( _
ByVal user_ID As System.Guid, _
ByVal user_Type As Integer, _
ByVal status As Integer, _
ByVal userName As String, _
ByVal password As String, _
ByVal secret_Question As Integer, _
ByVal secret_Answer As String, _
ByVal company As String, _
ByVal company_Type As Integer, _
ByVal first_Name As String, _
ByVal last_Name As String, _
ByVal address1 As String, _
ByVal address2 As String, _
ByVal city As String, _
ByVal state As String, _
ByVal zip As String, _
ByVal country As String, _
ByVal day_Phone As String, _
ByVal night_Phone As String, _
ByVal fax As String, _
ByVal email As String, _
ByVal web_Site As String) As Integer
Dim myConnection As New Connection
Dim connectionString As String = myConnection.ConnString
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "INSERT INTO [tblUser] ([User_ID], [User_Type], [Status], [UserName], [Password], " & _
"[Secret_Question], [Secret_Answer], [Company], [Company_Type], [First_Name], [L" & _
"ast_Name], [Address1], [Address2], [City], [State], [Zip], [Country], [Day_Phone" & _
"], [Night_Phone], [Fax], [Email], [Web_Site]) VALUES (@User_ID, @User_Type, @Sta" & _
"tus, @UserName, @Password, @Secret_Question, @Secret_Answer, @Company, @Company" & _
"_Type, @First_Name, @Last_Name, @Address1, @Address2, @City, @State, @Zip, @Coun" & _
"try, @Day_Phone, @Night_Phone, @Fax, @Email, @Web_Site)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_user_ID As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_user_ID.ParameterName = "@User_ID"
dbParam_user_ID.Value = user_ID
dbParam_user_ID.DbType = System.Data.DbType.Guid
dbCommand.Parameters.Add(dbParam_user_ID)
Dim dbParam_user_Type As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_user_Type.ParameterName = "@User_Type"
dbParam_user_Type.Value = user_Type
dbParam_user_Type.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_user_Type)
Dim dbParam_status As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_status.ParameterName = "@Status"
dbParam_status.Value = status
dbParam_status.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_status)
Dim dbParam_userName As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userName.ParameterName = "@UserName"
dbParam_userName.Value = userName
dbParam_userName.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_userName)
Dim dbParam_password As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_password.ParameterName = "@Password"
dbParam_password.Value = password
dbParam_password.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_password)
Dim dbParam_secret_Question As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_secret_Question.ParameterName = "@Secret_Question"
dbParam_secret_Question.Value = secret_Question
dbParam_secret_Question.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_secret_Question)
Dim dbParam_secret_Answer As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_secret_Answer.ParameterName = "@Secret_Answer"
dbParam_secret_Answer.Value = secret_Answer
dbParam_secret_Answer.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_secret_Answer)
Dim dbParam_company As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_company.ParameterName = "@Company"
dbParam_company.Value = company
dbParam_company.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_company)
Dim dbParam_company_Type As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_company_Type.ParameterName = "@Company_Type"
dbParam_company_Type.Value = company_Type
dbParam_company_Type.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_company_Type)
Dim dbParam_first_Name As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_first_Name.ParameterName = "@First_Name"
dbParam_first_Name.Value = first_Name
dbParam_first_Name.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_first_Name)
Dim dbParam_last_Name As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_last_Name.ParameterName = "@Last_Name"
dbParam_last_Name.Value = last_Name
dbParam_last_Name.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_last_Name)
Dim dbParam_address1 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_address1.ParameterName = "@Address1"
dbParam_address1.Value = address1
dbParam_address1.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_address1)
Dim dbParam_address2 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_address2.ParameterName = "@Address2"
dbParam_address2.Value = address2
dbParam_address2.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_address2)
Dim dbParam_city As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_city.ParameterName = "@City"
dbParam_city.Value = city
dbParam_city.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_city)
Dim dbParam_state As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_state.ParameterName = "@State"
dbParam_state.Value = state
dbParam_state.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_state)
Dim dbParam_zip As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_zip.ParameterName = "@Zip"
dbParam_zip.Value = zip
dbParam_zip.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_zip)
Dim dbParam_country As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_country.ParameterName = "@Country"
dbParam_country.Value = country
dbParam_country.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_country)
Dim dbParam_day_Phone As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_day_Phone.ParameterName = "@Day_Phone"
dbParam_day_Phone.Value = day_Phone
dbParam_day_Phone.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_day_Phone)
Dim dbParam_night_Phone As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_night_Phone.ParameterName = "@Night_Phone"
dbParam_night_Phone.Value = night_Phone
dbParam_night_Phone.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_night_Phone)
Dim dbParam_fax As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_fax.ParameterName = "@Fax"
dbParam_fax.Value = fax
dbParam_fax.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_fax)
Dim dbParam_email As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_email.ParameterName = "@Email"
dbParam_email.Value = email
dbParam_email.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_email)
Dim dbParam_web_Site As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_web_Site.ParameterName = "@Web_Site"
dbParam_web_Site.Value = web_Site
dbParam_web_Site.DbType = System.Data.DbType.StringFixedLength
dbCommand.Parameters.Add(dbParam_web_Site)

Dim rowsAffected As Integer = 0
dbConnection.Open()
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close()
End Try

Return rowsAffected
End Function


The Sub that calls the Insert function



Public Sub Add_New_User()
m_User_ID = New Guid 'm_User_ID is the private field for the public User_ID Property
myData.InsertOneUser( _
User_ID, _
User_Type, _
Status, _
UserName, _
Password, _
Secret_Question, _
Secret_Answer, _
Company, _
Company_Type, _
First_Name, _
Last_Name, _
Address1, _
Address2, _
City, _
State, _
Zip, _
Country, _
Day_Phone, _
Night_Phone, _
Fax, _
Email, _
Web_Site)

End Sub

View 2 Replies View Related

Inserting GUID Data

Jun 7, 2002

Hi everybody
I have a table named GrpMembership which has columns ParticipantId and InterestGroupId that have datatypes uniqueidentifier.When I try to run the following insert stmt:
insert into grpmembership
(guparticipantid,guInterestGroupId,bIsAdmin,dtCrea ted)
values
({EE0BC83E-01DD-4B0D-BFAA-34B508C28CF3}
{D149BD88-55B6-4EB9-AA81-1E1B5141EFA6},
0,6/7/2002)

it gives error:

[Microsoft][ODBC SQL Server Driver]Syntax error or access violation

Please Help

Regards
Jignesh

View 1 Replies View Related

Spliting A Recrod Into Two

Feb 14, 2008

HI if I have a recrod in a plain text file , and it has some colums information including FromDate and ThruDates if the date range is over 30 days, Then the record should split and becomes 2 records rather then one.

for example:

if i have FromDate 07/01/06 and ThruDate = 08/25/06

than
that single record should be saved as two records

like

Record#1 FromDate ThruDate

1 07/01/06 07/30/06
2 08/31/06 08/25/06


so what should I do to work it out, in the database, what could be the t sql or trigger that I have to use??? help please.

View 11 Replies View Related

I Can't Retrieve Data After Inserting It ?

Mar 1, 2008

Dears,
I'm using FormView to insert and retrieve data from SQL Server Database 2000. I'm using stored procedure to insert and display data by using C#.
Every time I insert the data, I can't retrive it. To retrieve all the inserted data, I have to close my website, and then reopen it again.
I close the connection every time after using the stored procedures, but nothing happened.
What do you think the problem is ??
 

View 3 Replies View Related

INSERT Command - Retrieve PK While Inserting To Table

Sep 16, 2009

I have a primary key named pk, name and surname fields. I need to insert to my table names and surnames.

INSERT INTO People (name,surname) VALUES ('john','black');

I'm not giving pks database gives is auto. But my problem is i need to know the pk that my database gave. Because i have lots of duplicate records. Is there any way to retrieve pk while inserting to table.

View 7 Replies View Related

Regarding Newid

Apr 9, 2007

Dear Folks,
can you please tell me, how many newid's can be generated by an sql server instance? and the newid generated by one instance can possibly be generated by another instance ? please give me brief regarding this


thank you very much

Vinod

View 1 Replies View Related

NEWID()

Nov 23, 2005

Is there a limitation of using:set @sessionID = NEWID()would there be a simular NEWID() being generated if used in a databaseapplication.Eugene Anthony*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

NewID

Mar 1, 2007

Hello,

I use VB.Net and SQL CE 2.0. I'd like to start using UniqueIdentifier fields as my primary keys.

I saw that this would return a NewID value


System.Guid.NewGuid().ToString()

however, it is not supported in Compact Framework. So how can one obtain the next NewId()?

Thank you.

View 1 Replies View Related

Newid() Question

Jul 10, 2006

when you use newid() is that a new uniqueidentifier for the database or for the table???I have a changelog that captures newly created users first and gives them a newid, then i want to approve that change and copy the newid generated for that user into the user table.  Will I run into duplicate id's that way???

View 1 Replies View Related

Need More SQL Query NewID Help

Jul 7, 2006

Excuse my ignorance because I don't do advance db related programming,but have no other choice at the moment. My experience is limited tosimple queries.I need to have the following query display the recordset in random orderbased on RecordID (unique key) if possible. I tried the ORDER BY NewID()at the end and it generated an error (ORDER BY items must appear in theselect list if SELECT DISTINCT is specified.) I guess because of the subquery. I would also like for the recordset to display a different 10records on each hit to the page, not just the same 10 records in randomorder. I wasn't sure if the SELECT commands I have in place aresufficient for this task.Thanks in advance for any assistance.SELECT DISTINCTTOP 10 dbo.ShowcaseRides.RecordID,dbo.ShowcaseRides.CustomerID, dbo.ShowcaseRides.PhotoLibID,dbo.ShowcaseRides.Year,dbo.ShowcaseRides.MakeShowcase,dbo.ShowcaseRides.ModelShowcase, dbo.ShowcaseRides.VehicleTitle,dbo.ShowcaseRides.NickName,dbo.ShowcaseRides.SiteURL,dbo.ShowcaseRides.ShowcaseRating, dbo.ShowcaseRides.ShowcaseRatingImage,dbo.ShowcaseRides.ReviewDate,dbo.ShowcaseRides.Home,dbo.ShowcaseRides.EntryDate, dbo.Customers.UserName,dbo.Customers.ShipCity, dbo.Customers.ShipRegion,dbo.Customers.ShipPostalCode,dbo.Customers.ShipCountry, dbo.Customers.LastName,dbo.Customers.FirstName, dbo.Customers.MemberSince,dbo.ShowcaseRides.Live,dbo.ShowcaseRides.MemberLive, dbo.Accessories.Make,dbo.Accessories.Model, Photos.PathFROM dbo.ShowcaseRides INNER JOINdbo.Customers ON dbo.ShowcaseRides.CustomerID =dbo.Customers.CustomerID INNER JOINdbo.Accessories ON dbo.ShowcaseRides.MakeShowcase= dbo.Accessories.MakeShowcase ANDdbo.ShowcaseRides.ModelShowcase =dbo.Accessories.ModelShowcase INNER JOIN(SELECT MIN(dbo.ShowcasePhotos.PhotoPath)AS Path, RecordIDFROM dbo.ShowcasePhotosGROUP BY RecordID) Photos ONdbo.ShowcaseRides.RecordID = Photos.RecordID INNER JOINdbo.ShowcasePhotos ON Photos.Path =dbo.ShowcasePhotos.PhotoPathWHERE (dbo.ShowcaseRides.MemberLive = 1) AND (dbo.ShowcaseRides.Live= 1) AND (dbo.ShowcaseRides.MakeShowcase = @MMColParam)ORDER BY dbo.ShowcaseRides.EntryDate DESCRegards,Darin L. MillerParadyse Development~-~-~-~-~-~-~-~-~-~-~-~-~-~-"Some things are true whether you believe them or not." - Nicolas Cagein City of Angels

View 3 Replies View Related

Cross Apply And Newid

Apr 28, 2008

Hi,

Why am I getting a different numbers of distinct ids in those queries?


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

select locations.*, T.c.value('.','nvarchar(max)') from
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
) as locations cross apply @myXml.nodes('(/lol)') T(c);

select mytable.* , T.c.value('.','nvarchar(max)') from
(
select newid() as Id
union
select newid()
) as mytable cross apply @myXml.nodes('(/lol)') T(c);


Thanks,

Victor

View 8 Replies View Related

Prob With Rowguid Using Newid() Fn

Apr 23, 2006

hi guys

cant find the prob, please help

ALTER TABLE [dbo].[tblUserDetails]
ALTER COLUMN [UserDetailRowGUID] [uniqueidentifier] set default newid()
go

error:Incorrect syntax near the keyword 'default'.

cm

View 2 Replies View Related

Cross Apply And Newid

Apr 28, 2008

I've been trying to figure out why these two return a different amount of distinct ids...
Is that a bug in optimization?




Code Snippet


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

WITH locations as
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
)
select locations.*, T.c.value('.','nvarchar(max)') from locations cross apply @myXml.nodes('(/lol)') T(c);

with mytable as
(
select newid() as Id
union
select newid()
)
select mytable.* , T.c.value('.','nvarchar(max)') from mytable cross apply @myXml.nodes('(/lol)') T(c);

View 4 Replies View Related

VIEWS With Columns Set By NEWID()

Sep 30, 2006

I have a view which at the moment has no unique identifier on each record. When I try adding a column definition to the view such as NEWID() as TransactionId, the view then cannot 1) be selected into a temporary table, or 2) queried on other columns in the table. In either case I end up with an empty result set.

I believe I have a way around this for my purpose, which was principally testability. However, can anyone enlighten me as to how and why this happens?

Andrew Raymond

View 5 Replies View Related

NewID(), UniqueIdentifier Is It Unique Across Different SQL Servers?

Apr 23, 2001

I have an application being developed using SQL server.
The data is captured at various remote areas and the
SQL servers are not physically connected to each other.

Periodically either through a replication / backup process
i plan to update the data from various servers into a central
database.

Can i use the NewID() function to generate a unique ID which
i can use as a primary key that would not be duplicated
across all these servers?

if not Please suggest a solution to maintain the uniqueness
of the transaction.

thanks in advance

View 1 Replies View Related

Distinct Random Rows Using NewID()

May 26, 2008

I have 2 tables, Artists and Artworks.
I have a query:

SELECT TOP (4) dbo.Artists.ArtistID, dbo.Artists.FirstName + ' ' + dbo.Artists.LastName AS FullName, dbo.Artworks.ArtworkName, dbo.Artworks.Image
FROM dbo.Artists INNER JOIN
dbo.Artworks ON dbo.Artists.ArtistID = dbo.Artworks.ArtistID
ORDER BY NEWID()

This query returns random images, but the artists are sometimes repeated.
I would like to have DISTINCT Random Artists returned, each with a random image. I tried various subqueries, but I just get error messages.
Any help would be appreciated.
Thnks,

Paolo

View 8 Replies View Related

Using NEWID() As A Parameter To A Stored Procedure

Jul 20, 2005

Is it possible to use NEWID() as a parameter to a stored procedure inSQL Server 2000. I keep getting a "Line 1: Incorrect syntax near ')'"error.ALTER PROCEDURE dbo.StoredProcedure1(@x uniqueidentifier)AS/* SET NOCOUNT ON */RETURNStoredProcedure1 NEWID()go"Line 1: Incorrect syntax near ')'"Thanks in advance

View 1 Replies View Related

I Think I Found A BUG With Either Newid() Or Derived Tables

Apr 3, 2008

Hello.So the scenario is a little complicated.I am joining two tables.Table 1 is derived; it has one row; it has a column based from newid()Table 2 joins to table 1 and reuses the newid() value from table 1 in table 2's rowsBecause there is only one row in Table 1, the value of newid() REPEATS in Table 2The bug is that the NewId() value from Table1 is REGENERATED with every Table 2 record.I created a blog about this because it takes a code sample to demonstrate:http://jerrytech.blogspot.com/2008/04/sql-2005-tsql-bug-with-newid-in-derived.html

Have a nice day;
Jerry

View 2 Replies View Related

SqlParameter With ParameterName '@NewID' Is Not Contained By This SqlParameterCollection

Mar 27, 2007

Hi,What I am trying to do is to get the new ID for every record is inserted into a table. I have a For...Each statement that does the loop and using the sqldatasource to so the insert.   <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ myConnectionString%>">
<InsertParameters>
<asp:Parameter Name="NewID" Type="int16" Direction="output" />
</InsertParameters>
</asp:SqlDataSource>  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sqlSelect As String
Session("Waste_Profile_Num") = 2
Session("Waste_Profile_Num2") = 5

sqlSelect = "SELECT Range, Concentration, Component_ID FROM Component_Profile WHERE (Waste_Profile_Num = " & Session("Waste_Profile_Num").ToString() & ")"
SqlDataSource1.SelectCommand = sqlSelect

Dim dv As Data.DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), Data.DataView)
For Each dr As Data.DataRow In dv.Table.Rows

sqlSelect = "INSERT INTO Component_Profile (Waste_Profile_Num, Range, Concentration, Component_ID) "
sqlSelect &= "VALUES (" & Session("Waste_Profile_Num2").ToString() & ", @Range, @Concentration, @Component_ID); SELECT @NewID = @@Identity"
SqlDataSource1.InsertCommand = sqlSelect
'SqlDataSource1.InsertParameters.Add("Waste_Profile_Num", Session("Waste_Profile_Num2").ToString())
SqlDataSource1.InsertParameters.Add("Range", dr("Range").ToString())
SqlDataSource1.InsertParameters.Add("Concentration", dr("Concentration").ToString())
SqlDataSource1.InsertParameters.Add("Component_ID", dr("Component_ID").ToString())
SqlDataSource1.Insert()
SqlDataSource1.InsertParameters.Clear()
MsgBox(Session("NewID").ToString())

Next

End Sub

Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted
Session("NewID") = e.Command.Parameters("@NewID").Value.ToString

End Sub  What I have done so far is to display the new id and I am going to use that return id later. However, the first time through the loop, I am able to get the new id but not the second time. So, I wonder, how do I every single new id each time the INSERT statement is executed?STAN   

View 5 Replies View Related

Problem Updating Existing Records With Newid()

Apr 23, 2008

I currently have a table called stores.  I've just added a uniqueidentifier column called store_guid to the stores table.  The table currently has about 500 records in it and now i'm trying to set each store_guid = to a newid().  I've tried using  UPDATE stores SET store_guid = newid()  .   however, that doesn't work because i think it's trying to set each record equal to the same guid using that approach.  All i need to do is fill in my new column with new guids.  any ideas?
 
Thanks in advance,
 

View 3 Replies View Related

Dynamic SQL And NewID Function - Pulling Random Records

Jun 11, 2007

I'm trying to use the NEWID function in dynamic SQL and get an errormessage Incorrect syntax near the keyword 'ORDER'. Looks like I can'tdo an insert with an Order by clause.Here's the code:SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'execute sp_executesql @SQLStringMy goal is to get a random percentage of records.The full SP follows. In a nutshell - I pull a set of records fromFD__Restart_Prog_Admit into a temporary table called FD__UR_Randoms.I need to retain the set of all records that COULD be eligible forselection. Based on the count of those records, I calculate how manyneed to be pulled - and then need to mark those records as "chosen".I'd just as soon not use the TMP_UR_Randoms table - I went that routebecause I ran into trouble with a #Tmp table in the above SQL.Can anyone help with this? Thanks in advance.Full SQL:CREATE PROCEDURE TP_rURRandomReview @ReviewType varchar(30)--Review type will fill using Crystal Parameter (setting defaults)AS/* 6.06.2007UR Requirements:(1) Initial 4-6 month review: 15% of eligible admissions(eligible via days in program and not yet discharged) must be reviewed4-6 months after admission. This review will be done monthly -meaning we'll have a moving target of names (with overlaps) whichcould be pulled from each month. (Minimum 5 records)(2) Subsequent 6-12 month review: Out of those already reviewed(in #1), we must review 25% of them (minimum of 5 records)(3) Initial 6-12 month review: Exclude any included in 1 or 2 -review 25% of admissions in program from 6-12 months (minimum 5)*/DECLARE @CodeRevType intDECLARE @PriorRec int -- number of records already markedeligible (in case user hits button more than once on same day for sametype of review)DECLARE @CurrRec int --number of eligible admitsDECLARE @RequFiles intDECLARE @SQLString nvarchar(1000)DECLARE @RequFilesSt varchar(100)DECLARE @CodeRevTypeSt char(1)DECLARE @TodayNotime datetimeDECLARE @TodaySt varchar(10)--strip the time off todaySELECT @TodayNotime = DateAdd(day,datediff(day,0,GetDate()),0)--convert the review type to a codeSelect @CodeRevType = Case @ReviewType when 'Initial 4 - 6 Month' then1 when 'Initial 6 - 12 Month' then 2 when 'Subsequent 6 - 12 month'then 3 END--FD__UR_Randoms always gets filled when this is run (unless it waspreviously run)--Check to see if the review was already pulled for this recordSELECT @PriorRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNotime)If @PriorRec 0 GOTO ENDThis--************************************STEP A: Populate FD__UR_Randomstable with records that are candidates for review************************If @CodeRevType = 1BEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 119)AND (DATEDIFF(d, Date_Admission, GETDATE()) <= 211)AND pa.OP__DOCID not in (Select Admit_DOCID from FD__UR_Randomswhere RecordChosen = 'T'))ENDIf @CodeRevType = 2--only want those that were selected in a batch 1 - in program 6-12months; selected for first reviewBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID in (Select Admit_DOCID from FD__UR_Randomswhere SelectType = 1 AND RecordChosen= 'T'))ENDIf @CodeRevType = 3--only want those that were not in batch 1 or 2 - in program 6 to 12monthsBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID NOT in (Select Admit_DOCID from FD__UR_Randomswhere SelectType < 3 AND RecordChosen= 'T'))ENDSELECT @CurrRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNoTime)--*************************************STEP B Pick the necessarypercentage **************************************--if code type = 1, 15% otherwise 25%If @CodeRevType = 1BEGINSELECT @RequFiles = (@CurrRec * .15)ENDELSEBEGINSELECT @RequFiles = (@CurrRec * .25)END--make sure we have at least 5If @RequFiles < 5BEGINSELECT @RequFiles = 5End--*************************************STEP C Randomly select thatmany files**************************************--convert all variables to stringsSELECT @RequFilesSt = Convert(Varchar(100),@RequFiles)SELECT @CodeRevTypeSt = Convert(Char(1),@CodeRevType)SELECT @TodaySt = Convert(VarChar(10),@TodayNoTime,101)SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'print @SQLStringexecute sp_executesql @SQLStringSELECT * FROM TMP_UR_Randoms/*--This select statement gives me what i want but I need to somehowmark these records and/or move this subset into the temp tableSelect Top @RequFilesFROM FD__UR_RandomsWHERE SelectType = @CodeRevType and SelectDate =Convert(varchar(10),GetDate(),101))ORDER BY NewID()*/ENDTHIS:GO

View 3 Replies View Related

Populate GUID Column In Table B With Values From GUID Column In Table A

Mar 4, 2008


How do I update the OrderGUID column in Table B with Values from OrderGUID column in Table A. I have already populated the OrderGUID column in Table A using NEWSEQUENTIALID(). Now I need to populate the OrderGUID column in Table B with Matching GUID values from the OrderGUID Column in Table A.

Does any one have a script to accomplish this task. thanks

View 4 Replies View Related

GUID&#39;s

Feb 1, 2001

we are currently using id's as primary key and replication is not part of our project.
will this be a problem if we decide to do replication? will microsoft generate an identifier then.
what is the advantages of using GUID now or doing it latter?

View 1 Replies View Related

GUID

May 26, 2006

Hello,

I'm working on a smart client app that has an offline sql express store and needs to work with several types of central databases (support for multiple products - ms sql, DB2 etc)

While trying to put together some offline functionality that needs the user to create records on the offline sql express data store, we've run into the need of being able to uniquely identify records so replicating the data in the offline store back into the primary database should not be a problem.

The data created offline spans many tables and involves several tables with relation ships - FK etc...Clearly not a simple case of store and forward.

We dont want to get into the mess of performing key replacement during a synch job with the server. Thats way too much trouble.

GUID seems like a good choice, but as always we have several stake holders having different opinions. And with databases other than MS SQL we will have to store them as strings.

To cut to the chase - can we not hash a GUID to get an integer while retaining atleast the same likelyhood of producing unique ids ? [no drop]

Thanks,

Aviansh



View 13 Replies View Related

Profile GUID

Apr 13, 2007

I am using a SqlDatasource and need to set a SelectParamter to the ProviderUserKey (The GUID of the user when Profiles are enabled)
 Can anyone tell me whether it is possible and How?
I am currently using the session state to store it in and then using the session=... to get the value into the parameter.
Is there a direct way of passing this value into a SelectParameter when using a SqlDataSource?
Thanks in advance.

View 3 Replies View Related

How To Specify A Guid In A WHERE Clause

Sep 25, 2007

Hi Everyone,
  I'm trying to create a SQL Delete statement using a string builder and the WHERE clause uses a Guid. Here is the code:stb.Append("DELETE FROM UserRights WHERE UserIDPtr = ");
stb.Append(TargetUserID);The resulting string is:  "DELETE FROM UserRights WHERE UserIDPtr = e01549fb-edf5-4668-de8b-b13dd5661a6e"
When I try to do an ExecuteNonQuery() using the string as the CommandText, I get an error.
Invalid column name 'e01549fb',Invalid column name 'edf5',Invalid column name 'de8b',Invalid column name 'b13dd5661a6e'
It is also strange that '4668' did not show up as an invalid column name, but I don't think that is relavent to this issue.
Can someone show me (or point me to an article) about using Guid's in a text string as a SQL command? Thanks in advance!

View 2 Replies View Related

GUID Issues

May 5, 2008

My database is using the membership store for all the user information. I added a tabel "Skills" with 3 fields "SkillID (GUID)" "SeekerID (GUID, This is the UserId)" and "SkillName ( Varchar(MAX))"
on the page i have a ListView setup to display the SkillName fields based on the SeekerID.
The original code was     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
          ' Get a reference to the currently logged on user          Dim CurrentUser As MembershipUser = Membership.GetUser
          ' Determine the currently logged on user's UserId value
          Dim SeekerID As Guid = CType(CurrentUser.ProviderUserKey, Object)
     End Subthat kept returning string to GUID conversion errors, so i had to change  Dim SeekerID As Guid = CType(CurrentUser.ProviderUserKey, Object) to Dim SeekerID As Object = CType(CurrentUser.ProviderUserKey.ToString(), Object) that appears to be working now. On the same page however, I want to insert records into the table, I tried 2 options both of which have a different problem.
     Option 1: Use a textbox (ID = NewSkill) and a button with the following code on it:
          Protected Sub SetNewSkill_Click(ByVal sender As Object, ByVal e As System.EventArgs)               Dim CurrentUser As MembershipUser = Membership.GetUser
               Dim SeekerGUID As Object = CType(CurrentUser.ProviderUserKey, Object)
 
               Dim NewSkill As TextBox = CType(FindControl("NewSkill"), TextBox)               Dim connectionString As String = ConfigurationManager.ConnectionStrings("QJSdatabase").ConnectionString()
               Dim insertSql As String = "INSERT INTO Skills(SeekerID, SkillName)VALUES(@SeekerGUID, @NewSkill)"               Using myConnection As New SqlConnection(connectionString)
                    myConnection.Open()                    Dim myCommand As New SqlCommand(insertSql, myConnection)
                    myCommand.Parameters.AddWithValue("@SeekerGUID", SeekerGUID)                    myCommand.Parameters.AddWithValue("@NewSkill", NewSkill.Text.Trim())
                    myCommand.ExecuteNonQuery()
                    myConnection.Close()
               End Using
          End Sub
 
     Problem: myCommand.Parameters.AddWithValue("@NewSkill", NewSkill.Text.Trim())  gets outlined and returns the error: Object reference not set to an instance of an object
 
     Option 2: Use a DetailsView linked to a SQLDataSource on the page
           <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="210px"
               AutoGenerateRows="False" DataSourceID="SqlDataSource2" DefaultMode="Insert">                    <Fields>
                         <asp:BoundField DataField="SkillName" HeaderText="Add Skill:" SortExpression="SkillName" />
                         <asp:CommandField ShowInsertButton="True" />
                         <asp:TemplateField InsertVisible="False">
                              <EditItemTemplate>
                                   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                              </EditItemTemplate>
                              <ItemTemplate>
                                   <asp:Label ID="Label1" runat="server"></asp:Label>
                              </ItemTemplate>
                    </asp:TemplateField>
               </Fields>
          </asp:DetailsView>
           <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:database %>"
               DeleteCommand="DELETE FROM [Skills] WHERE [SkillID] = @SkillID"                InsertCommand="INSERT INTO [Skills] ([SeekerID], [SkillName]) VALUES (@SeekerGUID, @SkillName)"
               SelectCommand="SELECT SkillName FROM [Skills]"
               UpdateCommand="UPDATE [Skills] SET [SkillName] = @SkillName WHERE [SkillID] = @SkillID">
                    <DeleteParameters>
                         <asp:Parameter Name="SkillID" Type="Object" />
                    </DeleteParameters>
                    <InsertParameters>
                         <asp:Parameter Name="SeekerGUID" Type="Object" />
                         <asp:Parameter Name="SkillName" Type="String" />
                    </InsertParameters>
                    <UpdateParameters>
                         <asp:Parameter Name="SkillName" Type="String" />
                         <asp:Parameter Name="SkillID" Type="Object" />
                    </UpdateParameters>
            </asp:SqlDataSource>
 
            http://junk.icore-studios.com/junk/Codeissues/postresumeerror.html
The @SeekerGUID is being generated by the same pageload code as the first chunk i gave (I have 2 variables SeekerID is the GUID converted to string to work with the ListView filter and SeekerGUID is the GUID)
 
Ultimatly getting either option to work would be fine. Though I think the second would be preferable because I think it'd be easier to replicate later on.
Thanks in advance for your time and any help

View 3 Replies View Related

GUID Troubles.

Apr 17, 2004

Hi,

I am having a hard time updating a database row using a UNIQUEIDENTIFIER. I retrieve the row into a datagrid and then use the GUID as a parameter to a stored procedure, but it doesn't update. If I run the query in SQL Analyser ... it works. Any ideas ? Here's my stored proc ... I tried passing a varchar and doing the conversion in the SP ... no go !! I am using MApplicationBlockD.


CREATE PROCEDURE spScanUpdate
@id varchar (100),
@name varchar (75)
AS
DECLARE @GUID_ID as uniqueidentifier
SELECT@GUID_ID = CAST ( @id as uniqueidentifier )

UPDATE tScan
SET name = @name
WHEREid = @GUID_ID
GO

View 5 Replies View Related

GUID Vs Integer

Apr 17, 2006

I use MS SQL Server 2005...Is there a structural advantage/disadvantage with using GUID as oposed to an integer?(also I use the sqltableprofileprovider and it doesnt seem to work with uniqueidentifiers)

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved