Navigation

Search

Categories

On this page

Getting column information using T-SQL
Getting a Record Count
SqlConnection.RetrieveStatistics()
Connection String has not been properly iniitialized
Database Connection Strings
Finding a column name in SQL Server
Closing a OleDB Database Connection That is Locked
Using SELECT to INSERT records
How to Insert Values into an Identity Column in SQL Server
Using XP_EXECRESULTSET To Obtain Database Size Information
SQL Web Data Administrator
Howto: use MySql with .Net

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 103
This Year: 41
This Month: 6
This Week: 2
Comments: 0

Sign In

 Wednesday, April 30, 2008
Wednesday, April 30, 2008 1:25:42 PM (Eastern Standard Time, UTC-05:00) (  |  )


SELECT ORDINAL_POSITION , COLUMN_NAME , DATA_TYPE , CHARACTER_MAXIMUM_LENGTH , IS_NULLABLE , COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyAwesomeTable' ORDER BY ORDINAL_POSITION ASC;
Another method is
sp_help 'tablename' 
 
 Monday, April 21, 2008
Monday, April 21, 2008 2:53:36 PM (Eastern Standard Time, UTC-05:00) (  |  )


There are a lot of ways to grab the number of records returned in a dataset.   This is one of my useful ones. Here is a working demo.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 
    Private Sub Page_Load()
        lblMovieCount.Text = GetMovieCount().ToString()
    End Sub
 
    Private Function GetMovieCount() As Integer
        Dim result As Integer = 0        

        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)

Dim cmd As New SqlCommand("GetMovieCount", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ReturnVal", SqlDbType.Int).Direction = ParameterDirection.Output Using con con.Open() cmd.ExecuteNonQuery() result = CType(cmd.Parameters("@ReturnVal").Value, Integer) End Using Return result End Function </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Movie Count</title> </head> <body> <form id="form1" runat="server"> <div> There are <asp:Label id="lblMovieCount" Runat="server" /> movies in the database. </div> </form> </body> </html>

GetMovieCount.sql

CREATE PROCEDURE dbo.GetMovieCount 
    -- OUTPUT parameter to hold the count. 
    @ReturnVal int OUTPUT 
AS 
    -- This will set @recordcount the the number of records returned by the SELECT query. 
    Set @ReturnVal = (SELECT COUNT(*) FROM Movies)
Monday, April 21, 2008 1:28:00 PM (Eastern Standard Time, UTC-05:00) (  |  )


The SqlConnection object has a new RetrieveStatistics method in .NET 2.0, which provides some interesting statistics that could come in handy while debugging and performance tuning your .NET applications.  Normally statistics are turned off by default, so you have to set StatisticsEnabled = true in order for the SqlConnection object to begin collecting statistics.  Here is a working demo.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
    Sub Page_Load()
        Dim connectionString As String = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
        Dim con As New SqlConnection(connectionString)
        Dim cmd As New SqlCommand("WAITFOR DELAY '0:0:03';SELECT Title,Director FROM Movies", con)
        con.StatisticsEnabled = True
        Using con
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
        End Using
        grdStats.DataSource = con.RetrieveStatistics()
        grdStats.DataBind()
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        td,th
        {
            padding:4px 20px;
        }
    </style>
    <title>Show All Statistics</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <h1>Connection Statistics</h1>
    
    <asp:GridView
        id="grdStats"
        AutoGenerateColumns="false"
        Runat="server">
        <Columns>
        <asp:BoundField DataField="Key" HeaderText="Key" />
        <asp:BoundField DataField="Value" HeaderText="Value" />
        </Columns>    
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>
 Wednesday, November 21, 2007
Wednesday, November 21, 2007 12:45:26 PM (Eastern Standard Time, UTC-05:00) (  |  |  )

I Was recently asked to move a standalone application inside of WSS 3.0. No matter what I tried I was getting an error message "Connection String has not been properly iniitialized" even though it worked fine in a separate app. The problem turned out to be that the first version which worked in version 1.1 does not work ASP.NET 2.0. In the first example, the connection string is pulling it's connection info from the <AppSettings> section. Version 2.0 doesn't use <appsettings> and instead uses <ConnectionStrings> so the SqlConnection and SqlCommand objects have to be structured a little differently.

********************

My typical method which worked fine in a separate app but did not work in WSS:

Dim strSQLText As String = "SELECT UserID, Name FROM tblUsers ORDER BY Name"
Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("QCentralConnectionString"))
Dim cmd As New SqlCommand(strSQLText, con)
con.Open()
ddluserID.DataSource = cmd.ExecuteReader()
ddluserID.DataBind()
con.Close()

web.config:

<appSettings>       
    <add key="QCentralConnectionString" value="server=localhost; database=QCentral; uid=xxx; pwd=xxx" />   
</appSettings>

********************

This version worked in WSS 3.0 (ASP.NET 2.0):

Dim strSQLText As String = "SELECT UserID, Name FROM tblUsers ORDER BY Name"
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("QCentralConnectionString").ConnectionString)
Dim cmd As New SqlCommand(strSQLText)
con.Open()
cmd.Connection = con
ddluserID.DataSource = cmd.ExecuteReader()
ddluserID.DataBind()
con.Close()

web.config:

<configuration>
<connectionStrings>
<clear />
<add name="QCentralConnectionString" connectionString="Data Source=localhost;Initial Catalog=QCentral;User ID=xxx;Password=xxx" providerName="System.Data.SqlClient" /> 
</connectionStrings>

********************

 Wednesday, November 14, 2007
Wednesday, November 14, 2007 9:31:10 AM (Eastern Standard Time, UTC-05:00) ( )

This is the most comprehensive site I've come across for creating connection strings for pretty much any database type you can think of

http://www.connectionstrings.com/

Technorati Tags: ,
 Tuesday, November 13, 2007
Tuesday, November 13, 2007 12:21:03 PM (Eastern Standard Time, UTC-05:00) (  |  )

Use this to find out where a given field name or column reside and is being used in SQL Server.

select so.name
from sysobjects so inner join syscolumns sc
ON so.id = sc.id where sc.name = 'YourColumnNameGoesHere'

or

select so.name, sc.name
from sysobjects so inner join syscolumns sc
ON so.id = sc.id where sc.name like '%YourPartialColumnNameGoesHere%'

or

Select table_name from information_Schema.columns where column_name='yourCol'

 

 Tuesday, October 16, 2007
Tuesday, October 16, 2007 8:02:16 PM (Eastern Standard Time, UTC-05:00) (  |  )

Often times when I'm developing a site for a client their budget permits that I use a low-cost or free database which means that I usually go with Access or MySQL.  Access has this nasty habit of not closing it's connection all of the time and the database is left in a "suspended" or locked state where the pages are not able to open another connection to it. I find that this happens sometimes even when I explicitly close the OleDBConnection. One solution is to run the bit of code below which has worked well for me.

** CloseDatabase.aspx.vb **

Partial Class CloseDatabase
   Inherits System.Web.UI.Page
End Class

** CloseDatabase.aspx **

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="CloseDatabase.aspx.vb" Inherits="CloseDatabase" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
Dim Conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("~/App_Data/mydbase.mdb"))

Sub Page_Load()
Dim ConnState As String = Conn.State.ToString()
If ConnState = "Open" Then
Try
Conn.Close()
Response.Write("The database was closed successfully.")
Catch Exc As Exception
Response.Write("The database was opened and could not be closed:<br />" & Exc.ToString().Replace(Environment.NewLine(), "<br />"))
End Try
ElseIf ConnState = "Closed" Then
Response.Write("There must be something else wrong... the database is already closed.")
Else
Response.Write("You should probably take up another career... the database was not opened OR closed... :| ")
End If
End Sub

</script>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

 Wednesday, September 26, 2007
Wednesday, September 26, 2007 2:51:56 PM (Eastern Standard Time, UTC-05:00) (  |  )

I found this article on one of my favorite sites on how to insert new records using an embedded SELECT statement.  Here is an example:

INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'

http://www.sqlteam.com/article/using-select-to-insert-records

 Wednesday, August 08, 2007
Wednesday, August 08, 2007 9:09:12 AM (Eastern Standard Time, UTC-05:00) (  |  )

Inserting a value into an identity column (primary key) is something I need to do often but usually forget how to do.  It's actually pretty easy so I made myself some notes on this topic.

If you try and run this in QA in SQL Server, you'll receive the error below because ID is the PK for tableA 

INSERT tableA(ID, TheValue)
VALUES (1, 'First Row')
GO

Msg 544, Level 16, State 1, Line 3
Cannot insert explicit value for identity column in table 'tableA' when IDENTITY_INSERT is set to OFF.

The trick is to enable IDENTITY_INSERT for the table like this

SET IDENTITY_INSERT tableA ON

INSERT tableA(ID, TheValue)
VALUES (3, 'First Row')

SET IDENTITY_INSERT tableA OFF

 Tuesday, June 26, 2007
Tuesday, June 26, 2007 10:01:39 PM (Eastern Standard Time, UTC-05:00) (  |  )

Came across this article and code which provides a script for obtaining the size of every database on your SQL Server 2000 box. Very nice...

http://www.sqlservercentral.com/columnists/jtshyman/usingxp_execresultsettoobtaindatabasesizeinformati.asp

Tuesday, June 26, 2007 9:56:40 PM (Eastern Standard Time, UTC-05:00) ( )

I came across this nifty web-based administrator for SQL Server from Codeplex.   I haven't tried it yet but it looks promising and it's open source.

 

 

 Thursday, June 07, 2007
Thursday, June 07, 2007 10:14:11 AM (Eastern Standard Time, UTC-05:00) ( )

Tim Mackey's Weblog entry explains this nicely

http://tim.mackey.ie/HowtoUseMySqlWithNet.aspx