I want to run a Transact SQL statement from within C# in order to create a login to SQL Server. It is important that I do it inside the code, without executing a .sql file from outside the program. How do I do that?

Following is the T-SQL statement I am going to use, which basically create a Windows Authentication based Login to SQL Server.

CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
GO

Help is greatly appreciated.

private void simpleButton2_Click(object sender, EventArgs e)
    {
      const string query = @"CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;";
      const string connStr = @"Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;";
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          cmd.ExecuteNonQuery();
        }
        conn.Close();
      }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.