Swap variables

Swap two variables x and y (having values X and Y respectively) without temporary storage:

x := x xor y;
y := x xor y;
x := x xor y;

The first line stores a "combination" of X and Y in x.

In the second line this "combination" is xor'ed with Y, resulting in the value X; this is stored in y.

In the third line the "combination" is again xor'ed with y (now containing the value X), resulting in the value Y; this is stored in x.

We can write this in one line of c-code:

x ^= y ^= x ^= y;

C++ string to numeric conversion

#include <string>
#include <sstream>
#include <iostream>

// the third parameter of from_string() should be one of std::hex, std::dec or std::oct
template <class T>
bool from_string(T &t, const std::string &s, std::ios_base & (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

int main()
{
  int i;
  float f;
  if (from_string<int>(i, std::string("ff"), std::hex))
    std::cout << i << std::endl;
  else
    std::cout << "from_string failed" << std::endl;

  if (from_string<float>(f, std::string("123.456"), std::dec))
    std::cout << f << std::endl;
  else
    std::cout << "from_string failed" << std::endl;

  return 0;
}

Access versus SQL Server: date/time constants

MS Access:

SQL Server:

MS Access

SQL Server

WHERE Format(Tijd, 'yyyymmdd') = '20070801'

WHERE (Tijd >= '20070801') AND (Tijd < '20070802')

SQL Server: 2 varianten:

Zie datetime_access_vs_sql.txt

How to get just the date from a datetime column in SQL Server?  SELECT DATEADD(d, 0, DATEDIFF(d, 0, datefield)) 

How to get the day of the week regardless of the DATEFIRST setting? SELECT (DATEPART(dw, '2009-12-17') + @@DATEFIRST) % 7 AS dw See also http://www.sqlservercentral.com/articles/DateFirst/69203/

Visual Basic: test if array has been initialised

In VB, when an array has been declared

  Dim myArr() as String

but has not yet been initialised, for example with

  ReDim myArr(6)
  ' or
  myArr = Split(SomeString)

it will not work to test for UBound, IsNull, IsEmpty, or Is Nothing

  UBound(myArr)       ' Error: Subscript out of range
  myArr Is Nothing    ' Error: Type mismatch
  IsNull(myArr)       ' Returns False
  IsEmpty(myArr)      ' Returns False

The only reliable way is to test with

  (not myArr) = True

This will return True if the array has not yet been initialised, and False otherwise. Note that

  (not myArr)         ' Returns -1
  (not myArr) = True  ' Returns True
  (not myArr) = False ' Returns False

but after initialising the array

  (not myArr)         ' Returns some other large negative number
  (not myArr) = True  ' Returns False
  (not myArr) = False ' Returns False

Because in both cases not myArr will return a negative number, something like

  IIf((not myArr), "yes", "no")

will always return "yes".

Visual Basic ISNULL probleem

Ik ben een aantal keer het volgende probleem tegengekomen (zie ook http://bvrolijk.net/2008/01/19/null-or-not-null/) dat de regel IIf(IsNull(rs!x), "", rs!x) een "Invalid use of Null" geeft. Ook als het wordt uitgeschreven als

  If IsNull(rs!x) Then
    ...
  Else
    ...
  End If

verschijnt dezelfde fout. Bij debuggen blijkt dat op de eerste regel, of bij de eerste keer opvragen, de waarde van rs!x ongelijk is aan null, maar daarna niet meer! De enige manier om het te omzeilen is om een variabele van het type Variant te gebruiken. Deze kan namelijk ook null bevatten. Op internet heb ik deze link gevonden: http://www.vbforums.com/showthread.php?t=546858. Het zou dus kunnen dat het te maken heeft met het oude ADODB, en dat het dus helpt over te stappen naar OLEDB / ADO.Net. Dit is natuurlijk geen kleinigheid. Maar het blijkt ook te maken te hebben met het datatype in de database. Velden met type nvarchar(MAX) en ntext geven problemen, maar na wijzigen in type text werkt het wel! Probleem met Unicode?

SQL Server: verwijder kolom met DEFAULT CONSTRAINT

' Bij SQL Server kan een kolom met DEFAULT CONSTRAINT niet zomaar verwijderd worden,
' omdat eerst de constraint verwijderd moet worden.
' Bij Access is dit geen probleem.
' Code om de naam van de CONSTRAINT te vinden:

  Dim strConstraint As String

  If CurrentDataBase = SQLServer Then
    strSql = "SELECT t.name AS tname, c.name AS cname, d.name AS dname, d.definition " & _
      "FROM sys.tables AS t INNER JOIN " & _
      "sys.default_constraints AS d ON d.parent_object_id = t.object_id INNER JOIN " & _
      "sys.columns AS c ON c.object_id = t.object_id AND c.column_id = d.parent_column_id " & _
      "WHERE (t.name = 'Afwezigheidsredenen') AND (c.name = 'AanvullenMaxAantalUur')"

    Call GetRecordset(strSql, DynaType, psnap)
    If (Not psnap.EOF) And (Not psnap.BOF) Then
      psnap.MoveFirst
      strConstraint = psnap!dname
    End If
    Call CloseRecordset(psnap)

  End If

  conn.Execute ("ALTER TABLE AfwezigheidsRedenen ADD tmpAanvullenMaxAantalUur REAL")
  conn.Execute ("UPDATE AfwezigheidsRedenen SET tmpAanvullenMaxAantalUur = AanvullenMaxAantalUur")

  If err.Number = 0 Then
    If CurrentDataBase = SQLServer Then
      If Len(Trim(strConstraint)) <> 0 Then
        conn.Execute ("ALTER TABLE AfwezigheidsRedenen DROP CONSTRAINT " & strConstraint)
      End If
    End If

    conn.Execute ("ALTER TABLE AfwezigheidsRedenen DROP COLUMN AanvullenMaxAantalUur")

    If err.Number = 0 Then
      conn.Execute ("ALTER TABLE AfwezigheidsRedenen ADD AanvullenMaxAantalUur REAL NOT NULL DEFAULT 0")
      conn.Execute ("UPDATE AfwezigheidsRedenen SET AanvullenMaxAantalUur = tmpAanvullenMaxAantalUur")
      conn.Execute ("ALTER TABLE AfwezigheidsRedenen DROP COLUMN tmpAanvullenMaxAantalUur")
    End If
  End If

ProgrammingTricks (last edited 2010-02-19 08:02:20 by BenjaminVrolijk)