c# - SELECT @@IDENTITY giving Specified Cast is not Valid? -
this question has answer here:
- scope_identity() guids? 5 answers
hope can this
i trying insert row of data table [issues] guid id column of issues can inserted table actions, creating link between two. relationship [issues]one many[actions].
when run code causes specified cast not valid error here: guid lastid = (guid)sel.executescalar();
lastid variable want assign last guid created can passed table insert table actions.
if can great! thanks
i using c# 2010 express
//this declared @ top of form public guid lastid; private void pbsaveissue_click(object sender, eventargs e) { sqlceconnection arcbaseconn = new sqlceconnection(@"data source=|datadirectory|\arcbase.sdf"); try { string cmdissuesubmit = "insert issues (type,description,dateraised,site,reportedby,status) values (@type,@description,@dateraised,@site,@reportedby,@status)"; string typesubmit = cbissuetype.text; string descriptionsubmit = rtbdescription.text; string sitesubmit = cbissuesite.text; string reportedbysubmit = cbreportedby.text; string dateraisedsubmit = dtpdateraised.text; sqlcecommand sel = new sqlcecommand(); sel.connection = arcbaseconn; sel.commandtype = commandtype.text; sel.commandtext = cmdissuesubmit; sel.parameters.addwithvalue("@type", typesubmit); sel.parameters.addwithvalue("@description", descriptionsubmit); sel.parameters.addwithvalue("@dateraised", dateraisedsubmit); sel.parameters.addwithvalue("@site", sitesubmit); sel.parameters.addwithvalue("@reportedby", reportedbysubmit); sel.parameters.addwithvalue("@status", lbstatus.text); arcbaseconn.open(); sel.executenonquery(); //here problem // grab last unique id issue entered , assign variable can entered actions below. string cmdgetlastid = "select @@identity"; sel.commandtext=cmdgetlastid; guid lastid = (guid)sel.executescalar(); arcbaseconn.close(); } catch (sqlceexception ex) { messagebox.show(ex.message, application.productname, messageboxbuttons.ok, messageboxicon.error); application.exitthread(); }
assuming table inserting has identity column defined,
- identity columns must integer types (
tinyint
,smallint
,int
orbigint
), notguid
, castingguid
won't work (as discovered). - you want use
@@scope_identity
instead of@@identity
, lest discover pain caused race conditions.
from looks of code, aren't doing this, but...
if trying value of column defined uniqueid
(and don't have race condition), need this:
declare @my_guid uniqueid = newid() insert issues ( type , description , dateraised , site , reportedby , status , unique_guid_column ) values ( @type , @description , @dateraised , @site , @reportedby , @status , @my_guid ) select case @@error when 0 @myguid else null end
and execute using executescalar()
.
Comments
Post a Comment