Pages

Assigning values to SQL variable using Select Query


Assigning a value to SQL variable:
Declare @date Datetime
set @date = getdate()

We can achieve the same using simple select statement:
select @date = getdate()

If we try to do the same from a result of query, then it will be

select @date = DateCreated from SomeTable where PrimaryKey = SomeValue

We are sure that this query will return only one record, so this statement is valid and always returns expected result. In a scenario, where the result is more than one then which value will be assigned to that variable. Will it be first record or last record or anything in between?

declare @empid char(8)
select top 10 @empid = empid from Empmaster where DeptID = 'A' order by empid
select top 10 * from Empmaster where DeptID = 'A' order by empid
select @empid

It will always get assigned to the last result data. So to be on the safe side we need to put the order by clause and use the appropriate order as ascending or desending considering the fact it always pull the last record. Otherwise we need to use the “Top 1” so it always use the value of first record in the result with proper sorting.

Handling Ajax Asynchronous Post Back Error

I read this solution in one of the article, just want to share the same. 


1. We can handle ajax errors from client side by adding a custom handler to end_request event of PageRequestManager object. 
2. We can handle this by binding a error handler method to property OnAsyncPostBackError of Script manager object.


Client side handling:
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
  if (args.get_error() != undefined) {
    var errorMessage;
    if (args.get_response().get_statusCode() == '200') {
      errorMessage = args.get_error().message;
    }
    else {                
      // Error occurred somewhere other than the server page.
      errorMessage = 'An unspecified error occurred. ';                                }
    args.set_errorHandled(true);                
  }
}
</script>

Server side handling:
<asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"></asp:ScriptManager>
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e){
  if (e.Exception.Data["ExtraInfo"] != null){
    ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message + e.Exception.Data["ExtraInfo"].ToString();
  }
  else{
    ScriptManager1.AsyncPostBackErrorMessage = "An unspecified error occurred."
  }
}