Note that there are some explanatory texts on larger screens.

plurals
  1. POASP function not returning mssql insert id
    primarykey
    data
    text
    <p>Having a strange issue with a mssql insert and trying to retrieve the insert id trough a function call. The strange thing is the last insert id is fetched and I can print it out in the function but it returns an empty value via the function if I structure my sql statement in the following way: </p> <pre class="lang-vbs prettyprint-override"><code>function sqlInsert(table, byVal fieldList) sqlInsert = 0 ' default in case of error .... ' removed code that builds sql for simplicity sql = "insert into " &amp; table &amp; " (" &amp; insertFields &amp; ") values (" &amp; insertValues &amp; ")" sql = "SET NOCOUNT ON;" &amp; sql &amp; "; SELECT SCOPE_IDENTITY() AS NewID" set rs = oCn.Execute(sql) response.write rs("NewID") ' 28 for example sqlInsert = rs("NewID") ' empty!! end function </code></pre> <p>The function works and executes the insert statement correctly and rs("NewID") <strong>does</strong> contain the correct inserted row id. However, nothing is returned to the function call. eg: </p> <pre class="lang-vbs prettyprint-override"><code>result = sqlInsert("tablename", data) response.write result 'empty!! </code></pre> <p>If I seperate the sql as follows: </p> <pre class="lang-vbs prettyprint-override"><code>sql = "insert into " &amp; table &amp; " (" &amp; insertFields &amp; ") values (" &amp; insertValues &amp; ")" set rs = oCn.Execute(sql) set rs2 = oCn.Execute("SELECT SCOPE_IDENTITY() AS NewID") response.write rs2("NewID") '28 for example sqlInsert = rs2("NewID") '28 </code></pre> <p>....then that works and the result of the function call contains the insert ID.</p> <pre class="lang-vbs prettyprint-override"><code>result = sqlInsert("tablename", data) response.write result '28 </code></pre> <p>in both cases, the recordset contains the correct insert id in the "NewID" but only second method returns the id to the function call. Why? I have tried <code>cInt(rs("NewID"))</code> in the first example but still nothing. </p> <p>I know I could just use the second method but the first is one less call to the database and I just want to know why it doesn't return the value when clearly the value is present in the rs value if I write it out before assigning it to sqlInsert.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload