VB SQL Server Ignoring Default Values - sql-server

I'm using some simple vb code to log a users login to my program. The idea is that the Server uses default values to automatically fill in the time / date columns with the correct time/date. I know I can retrieve both of these from the client computer, but this is reliant on their device being set to the right time and time zone. I can't seem to get the server to use the default value when I use the below code. Both my columns seem to resort to 00:00:00 (for the time one) and 1900:01:01 (for the date column). But when I use Microsoft SQL Server Management Studio to in put fake data it correct defaults to the current time and date.
con.open()
cmd = New SqlCommand("INSERT INTO Account_Login_Log VALUES (#memberID, #accountID, #logintime, #logindate)", con)
cmd.Parameters.AddWithValue("#memberID", "32")
cmd.Parameters.AddWithValue("#accountID", "91")
cmd.Parameters.AddWithValue("#logintime", "")
cmd.Parameters.AddWithValue("#logindate", "")
cmd.ExecuteNonQuery()
con.close()
My question is, why isn't my code automatically defaulting at the server end to the correct time and date?
I have tried:
Omitting the columns from my insert statement, using the dbNULL.value and also simply specifying "" as I have shown in my code above. But all resort to the beginning of time.
Edit - I have included my complete table definitions below.
USE [Atlas]
GO
/****** Object: Table [dbo].[Account_Login_Log] Script Date: 26/01/2015 8:34:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Account_Login_Log](
[lLogID] [int] IDENTITY(10,1) NOT NULL,
[lMember_ID] [int] NOT NULL,
[lAccount_ID] [int] NOT NULL,
[lLogin_Time] [time](7) NOT NULL CONSTRAINT [DF_Account_Login_Log_lLogin_Time] DEFAULT (CONVERT([varchar](8),getdate(),(108))),
[lLogin_Date] [date] NOT NULL CONSTRAINT [DF_Account_Login_Log_lLogin_Date] DEFAULT (getdate()),
CONSTRAINT [PK_Account_Login_Log] PRIMARY KEY CLUSTERED
(
[lLogID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Account_Login_Log] WITH CHECK ADD CONSTRAINT [FK_Account_Login_Log_Account1] FOREIGN KEY([lAccount_ID])
REFERENCES [dbo].[Account] ([aAccount_ID])
GO
ALTER TABLE [dbo].[Account_Login_Log] CHECK CONSTRAINT [FK_Account_Login_Log_Account1]
GO
ALTER TABLE [dbo].[Account_Login_Log] WITH CHECK ADD CONSTRAINT [FK_Account_Login_Log_Member_Details] FOREIGN KEY([lMember_ID])
REFERENCES [dbo].[Member_Details] ([mMember_ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Account_Login_Log] CHECK CONSTRAINT [FK_Account_Login_Log_Member_Details]
GO
Edit - I've included the proof that my column does have the default value as getdate(), and the lLogin_Time is (CONVERT([varchar](8),getdate(),(108)))
Injection Attack Note: My code does not take any values from the user, all of this is calculated based off of program & database values, so I am not worried about an injection attack.

Change you code to
Dim cmd = new SqlCommand("INSERT INTO Account_Login_Log " & _
"(lMember_ID, lAccount_ID) " &
"VALUES (#memberID, #accountID)", cnn)
cmd.Parameters.AddWithValue("#memberID", 32)
cmd.Parameters.AddWithValue("#accountID", 91)
cmd.ExecuteNonQuery()
To AddWithValue you should pass the correct datatype. If the column expects a string you should pass a string, but if the column expects an int you pass an int,not a string. Moreover your INSERT doesn't need to pass values for the columns that have a default value. If you don't pass anything the default will be used. Finally the INSERT syntax requires that, if you don't pass parameters for all the field names you need to specify which columns are affected by your query. So you need to add the names of the two columns updated
A interesting reading about AddWithValue

I ended up dropping the table and recreating it with the datetime in the one column. I'm still not exactly sure why the server was defaulting to the start of the calendar, the only thing that seems logical is that VB was sending some sort of data to the columns and it was defaulting to the start instead of the current datetime. I've included my new table and it's code just incase anyone stumbles across the same issue in the future, though I doubt anyone will.
The VB Code:
con.open()
cmd = New SqlCommand("INSERT INTO Account_Login_Logger (lAccount_ID) VALUES (#accountid)", con)
cmd.Parameters.AddWithValue("#accountid", 91)
cmd.ExecuteNonQuery()
con.close()
The New Database Table:
USE [Atlas]
GO
/****** Object: Table [dbo].[Account_Login_Logger] Script Date: 27/01/2015 3:37:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Account_Login_Logger](
[lLogin_ID] [int] IDENTITY(10,1) NOT NULL,
[lAccount_ID] [int] NOT NULL,
[lDate_Time_Stamp] [datetime] NOT NULL CONSTRAINT [DF_Account_Login_Logger_lDate_Time_Stamp] DEFAULT (getdate()),
CONSTRAINT [PK__Account___0B8A2E93BF56F461] PRIMARY KEY CLUSTERED
(
[lLogin_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
My problem was resolved when I did this. Thank you for your help everyone.

Why do you think
INSERT INTO Account_Login_Log (lMember_ID, lAccount_ID, lLogin_Time, lLogin_Date) VALUES (#memberID, #accountID, #logintime, #logindate)
Will use default values?
If you have default values set for the table do this instead:
INSERT INTO Account_Login_Log (lMember_ID, lAccount_ID) VALUES (#memberID, #accountID)
Because you are passing values to the insert statement it uses those instead of the default.
The reason why Query Manager is working differently is because when you use the C# platform it is converting what you are sending to the correct type (time and date) and then sending values to the server which are used.

Related

SQL Server table only one Active Record at a given time

I have a SQL Server 2016 table where only one record should be active at any given time. There will be CRUD operations to it.
I am trying to create a unique nonclustered index on that table so that it has only 1 active record at any time. Criteria for active record is if today's date is between StartDate and StopDate. ID is a unique key. For the rest, I am not sure if my syntax and strategy is correct.
Here is my SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[GWFO_FlashNewsItem]
(
[ID] [INT] IDENTITY(1,1) NOT NULL,
[Title] [VARCHAR](150) NOT NULL,
[NavigateToURL] [VARCHAR](250) NULL,
[StartDate] [SMALLDATETIME] NOT NULL,
[StopDate] [SMALLDATETIME] NULL,
[Active] [BIT] NOT Null,
[UpdateSOEID] [CHAR](7) NULL,
[UpdateDate] [SMALLDATETIME] NULL,
CONSTRAINT [PK_GWFO_FlashNewsItem]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE UNIQUE NONCLUSTERED INDEX uixf_GWFO_FlashNews_Active_filtered
ON GWFO_FlashNewsItem (Active)
INCLUDE (ID, Title)
WHERE Active = 1
I think you need to identify more clearly what you need first. For example, you have a record with Active bit set, StartDate is today 0:00:00, StopDate is today 23:59:59, everything is fine.
Until it's 23:59:59, when your condition (Active bit should be set only when GetDate() is between StartDate and StopDate) is not valid anymore. What do you think should happen at that second? That bit magically converted to 0, just by itself?
Another question, should your requirements allow records to have Active set to 0 even if the condition is satisfied? If the answer to this question is "no", then your active bit is not separate field, but simply a [non-deterministic] function of StartDate and StopDate, and your only concern is to not allow overlapping intervals.
From the context it seems as if you are attempting to limit a record from being inserted or updated that contains a date range that is not in the current date. In order to do that you could use a trigger. If the date range does not meet your criteria of being active you can raise an error and prevent the insert or update from occurring.
I also just tried creating a check constraint and that works as well:
CREATE TABLE [dbo].[test]
(
[d1] [DATETIME] NULL,
[d2] [DATETIME] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[test] WITH CHECK
ADD CONSTRAINT [CK_test] CHECK ((GETDATE() >= [d1] AND GETDATE() <= [d2]))
GO
ALTER TABLE [dbo].[test] CHECK CONSTRAINT [CK_test]
GO
This code:
INSERT INTO test SELECT '1/1/2000', '1/1/2001'
Throws this error:
Msg 547, Level 16, State 0, Line 24
The INSERT statement conflicted with the CHECK constraint "CK_test". The conflict occurred in database "SysproSupport", table "dbo.test". The statement has been terminated.
Ultimately though it seems that you should be able to control the types of records that you are manipulating with your front end. If you have an application or data entry interface that is manipulating your data, you can put these constraints into it. Implementing this as a constraint or trigger will ensure not even an administrator can clean data without disabling them.

Alter GENERATED ALWAYS colum into a GENERATED BY DEFAULT identity column - Sql Server

I need to change the Existing Table Column, which is configured as GENERATED ALWAYS into a GENERATED BY DEFAULT.
Sample Table Structure
CREATE TABLE [dbo].[Contact](
[ContactID] [uniqueidentifier] NOT NULL,
[ContactNumber] [nvarchar](50) NOT NULL,
[SequenceID] [int] IDENTITY(1,1) NOT NULL,
[SysStartTime] [datetime2](0) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndTime] [datetime2](0) GENERATED ALWAYS AS ROW END NOT NULL,
CONSTRAINT [PK_Contact] PRIMARY KEY NONCLUSTERED
(
[ContactID] ASC
)WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY],
PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ContactHistory],
DATA_CONSISTENCY_CHECK = ON )
)
This is the table I'm already having now I need to change the column
[SysStartTime] to GENERATED BY DEFAULT from GENERATED ALWAYS
I tried the following code
ALTER TABLE dbo.Contact ALTER column SysStartTime SET GENERATED BY DEFAULT
But it throws an error
Msg 156, Level 15, State 1, Line 19 Incorrect syntax near the keyword
'SET'.
Kindly assist me.
I know this is an old question, but I stumbled on a similar problem and I found a way to achieve an end result equivalent to the one desired here (have the records tell the correct story of when they were created and also properly work with temporal queries).
What I did was:
Created both tables (the primary and it's history)
Loaded the primary table with it's data
Updated all records in the primary table without changing any data. This causes an equivalent record to be created in the history table
Disabled system versioning in the table with ALTER TABLE Contact SET (SYSTEM_VERSIONING = OFF);
Updated the ValidFrom field in the history table to properly reflect the date the records where actually originally inserted. (this can only be done if the system versioning for the table is disabled)
Re enabled the system versioning in the table using ALTER TABLE Contact SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ContactHistory], DATA_CONSISTENCY_CHECK = ON ))
This causes the records to be identical (except for the ValidFrom/To fields), but allow for any query using FOR SYSTEM_TIME AS OF 'YYYY-MM-DD THH:mm:SS.0000000'; to work properly and represent the data exactly as it was in the moment requested.
Things I found out when trying this:
You can't change an existing field to be GENERATED ALWAYS AS ROW START/END. It needs to be a field set that way from the beginning.
You can't use DATETIMEOFFSET fields for the period fields.
There is no way to set the value in the period fields in the main table
There is no way to manipulate the data in the history table if versioning is enabled
Additional documentation:
https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver15

Why does this insert statement not match the table?

I am using a Visual Studio 2015 Database Project to attempt to insert rows into database tables which have been created by the project. The Insert sql works in the same table in SSMS, but not when run via the project.
I get the error: Column name or number of supplied values does not match the table definition.
TSQL insert script:
if not exists (select top 1 1 from [dbo].[PricingGroupTypes]) begin
INSERT INTO [dbo].[PricingGroupTypes]
([Name])
VALUES
('User')
,('Product Format')
print 'Pricing Group Types added'
end
Table Definition (in DB project):
CREATE TABLE [dbo].[PricingGroupTypes] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (250) NOT NULL,
CONSTRAINT [PK_PricingGroupTypes] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Table Definition (via ssms):
USE [Toyland]
GO
/****** Object: Table [dbo].[PricingGroupTypes] Script Date: 11/14/2016 11:05:05 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PricingGroupTypes](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](250) NOT NULL,
CONSTRAINT [PK_PricingGroupTypes] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Other inserts in the same script do not seem to fail, but the overall script will roll back so the database is empty after execution. And, like I said, the exact same script WORKS when I run it in SQL Server Management Studio.
Perhaps there's some Visual Studio setting I'm missing, but this is about the most straightforward bit of script in the entire project, so you can see why I'm perplexed.
In the end, there was a comment here suggesting it was perhaps a problem with some other part of my overall script generated by the project. This turned out to be the case. I have now resolved the issue and the code in the original question is unchanged.
Unfortunately I don't know, anymore, which other part of the big script was the culprit, since I had to go through and make a few other changes to get everything running smoothly, but there did not appear to be any problems with the SQL in my original question.
if not exists (select top 1 1 from [dbo].[PricingGroupTypes]) begin
INSERT INTO [dbo].[PricingGroupTypes]
([Name])
VALUES
('User')
,('Product Format')
print 'Pricing Group Types added'
end
Your problem is that you're trying to insert two values into one column. Trying to insert 'User' and 'Product Format' into [Name] will kick back an error because it needs a destination for product format. Update your insert statement to include the second column and it should go.

DTS Package Terminates because of Duplicate Key Row

We have an old DTS Package that our SQL 2000 Server uses to push Employee records out to machines on our manufacturing floor.
Recently, we upgraded one of the machines, and it now is running SQL 2008 Express.
We have reconfigured the DTS Package to push the Employee records out to this new Server, but now we are getting this error message:
FETCH_EMPLOYEES:
The statement has been terminated. Cannot insert duplicate key row in object 'dbo.Users' with unique index 'IX_tblUsers_OpID'.
If I remote into our SQL 2000 Server, I can Right-Click to execute each step of the DTS Package in succession with NO errors.
So, I log onto this machine's SQL 2008 Express instance to see if I can figure anything out.
Now I am looking at the FETCH_EMPLOYEES stored procedure:
PROCEDURE [dbo].[FETCH_EMPLOYEES] AS
DECLARE #OpID varchar(255)
DECLARE #Password varchar(50)
DECLARE Employee_Cursor CURSOR FOR
SELECT OpID, Password
FROM dbo.vw_Employees
OPEN Employee_Cursor
FETCH NEXT FROM Employee_Cursor
INTO #OpID,#Password
WHILE ##FETCH_STATUS = 0
BEGIN
insert into dbo.Users (OpID,Password,GroupID)
VALUES (#OpID,#Password,'GROUP01')
FETCH NEXT FROM Employee_Cursor
INTO #OpID,#Password
END
CLOSE Employee_Cursor
DEALLOCATE Employee_Cursor
I don't really understand Cursors, but I can tell that the data is being pulled from a view called vw_Employees and being inserted into the table dbo.Users.
The view vw_Employees is simple:
SELECT DISTINCT FirstName + ' ' + LastName AS OpID, Num AS Password
FROM dbo.EmployeeInfo
WHERE (Num IS NOT NULL) AND (FirstName IS NOT NULL)
AND (LastName IS NOT NULL) AND (Train IS NULL OR Train <> 'EX')
So, now it seems the problem must be from the table dbo.Users.
I did not see anything particularly attention getting with this, so I scripted this table using a CREATE TO Query Editor and got this information that I don't really understand:
CREATE TABLE [dbo].[Users](
[ID] [int] IDENTITY(1,1) NOT NULL,
[OpID] [nvarchar](255) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[GroupID] [nvarchar](10) NOT NULL,
[IsLocked] [bit] NOT NULL,
CONSTRAINT [PK_tblUsers] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH CHECK ADD CONSTRAINT [FK_tblUsers_tblGroups] FOREIGN KEY([GroupID])
REFERENCES [dbo].[Groups] ([GroupID])
GO
ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_tblUsers_tblGroups]
GO
ALTER TABLE [dbo].[Users] ADD CONSTRAINT [DF_tblUsers_IsLocked] DEFAULT ((0)) FOR [IsLocked]
GO
OK, I feel the problem is somewhere in this table definition, but I don't really understand what it is doing (after creating the basic table).
It has a CONSTRAINT section with lots of variables I do not understand, then it is altering these tables to add FOREIGN KEY and CONSTRAINTS.
My Question: Could someone help me understand what the error is telling me (other than there is some duplicate key violation).
What column could be throwing a duplicate key violation?
Did I include enough data and screenshots?
UPDATE:
Based on Comments, it sounds like this screenshot is needed.
In the Users table, there is a list of Indexes, and one called IX_tblUsers_OpID says it is Unique and Non-Clustered.
I think we have eliminated duplicate Op_ID values on our source data table EmployeeInfo by finding all of them with this script:
select num as 'Op_ID', count(num) as 'Occurrences'
from employeeInfo
group by num
having 1<count(num);
This should have gotten rid of all of my duplicates. Right?
We purchase manufacturing machines that come configured with PCs for storing local data. They supply these script I have posted up, so I cannot comment on why they picked what they did. We just run a job that pulls the data onto our server.
Having columns with unique values has always been of high value on any dataset. This constrain can be added to any column, or index.
The error you receive is very clear and very specific. It literally gives the answer.
The statement has been terminated. Cannot insert duplicate key row in object 'dbo.Users' with unique index 'IX_tblUsers_OpID'.
It says "NO duplicates.... UNIQUE index..." then it tells you the name of the constrain "IX_tblUsers_OpID".
Now keeping that in mind, you are trying to insert in that column values you craft on the fly by concatenating two strings; name, plus last name.
What are the chances to come up with two of them being "John Smith"? High, very high!
Possible solutions:
You may remove the constrain and allow duplicates.
Modify the query so the values that tries to insert are -indeed- unique.
Use 'WITH (IGNORE_DUP_KEY = ON)' Reference: index_option (Transact-SQL)
Another guy here at work found this hidden feature, which solves the immediate problem but could cause other unknown issues.
In the Users table designer view, we can Right-Click on the OpID column, select Indexes/Keys..., locate this created IX_tblUsers_OpID key and change it's Is Unique value:
That seemed to have made it so that the DTS Package will run, and that is what we have going on right now.
I went back to the original EmployeeInfo table on our SQL 2000 Server to check for duplicate OpID values using this script:
select FirstName + ' ' + LastName as 'OpID',
Count(FirstName + ' ' + LastName) as 'Occurrences'
from EmployeeInfo
group by FirstName + ' ' + LastName
having 1 < count(FirstName + ' ' + LastName)
...but there were no records returned.
I'm not sure why the DTS Package was failing or why we had to turn off the Unique feature.
If anyone, at some time down the road, comes up with a better fix for this, please post!

Web-Service: How to authenticate users with the SQL Server database table using VB

Can somebody tell me how to authenticate users with the SQL Server database table using VB as a web service. I managed to connect to the SQL server via this VB code;
Public Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=421"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Sub
Any one ?Thank you in advance.
I would recommend that you first go through basic tutorials on SQL server as well as ADO.Net and then post questions. This will help in making your concepts clear as well as any help can be provided in more focused, problem areas. BTW, no hard feelings, just want you to be comfortable on programming. :)
Step 1 :
Create relevant database tables. These may include a users table and other tables such as roles, etc...
EDIT : You can use SQL scripts to create tables in DB. Please find a sample below.
-- Sample Table Creation and Index Creation script for MCIS-4423
-- This script is designed to be "re-runnable", but you need to be careful,
-- Since this will DROP the table, which would be bad if it was an existing table with data
-- Make sure you are in the correct database
USE [AdventureWorks]
GO
-- Drop Check Constraint
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK_Team_TeamID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Team]'))
ALTER TABLE [dbo].[Team] DROP CONSTRAINT [CK_Team_TeamID]
GO
-- Drop Table
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Team]') AND type in (N'U'))
DROP TABLE [dbo].[Team]
GO
-- Create Table
CREATE TABLE [dbo].[Team](
[TeamID] [char](3) NOT NULL,
[TeamName] [varchar](20) NOT NULL,
[City] [varchar](50) NOT NULL,
[StateCode] [char](2) NULL,
[PostalCode] [char](5) NULL,
CONSTRAINT [PK_Team] PRIMARY KEY CLUSTERED
(
[TeamID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
-- Add Check Constraint
ALTER TABLE [dbo].[Team] WITH CHECK ADD CONSTRAINT [CK_Team_TeamID] CHECK (([TeamID] like '[A-Z][A-Z][A-Z]'))
GO
ALTER TABLE [dbo].[Team] CHECK CONSTRAINT [CK_Team_TeamID]
GO
-- Drop index if it exists
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Team]') AND name = N'IX_Team_TeamName')
DROP INDEX [IX_Team_TeamName] ON [dbo].[Team] WITH ( ONLINE = OFF )
GO
-- Add non-clustered index on StateCode column
-- Use ONLINE = ON if you have Developer or Enterprise Edition
-- Use MAXDOP = 2 (set to roughly 25% of the number of CPU cores to keep index creation from affecting performance)
CREATE NONCLUSTERED INDEX [IX_Team_TeamName] ON [dbo].[Team]
(
[StateCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = ON, MAXDOP = 2, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
Please note that this sample is copied from http://sqlserverperformance.wordpress.com/2007/09/27/sample-table-and-index-creation-script-for-sql-server-2005/ and all credit related to its content goes to the author who wrote it.
Step 2 :
Write SQL query to find a user based on his username and password. You may go for password encryption, but that is out of scope for current question.
EDIT : Sample query can be as follows :
SELECT username FROM users
WHERE username=#username and password=#password
You can read through SqlCommand documentation here to understand how to add parameters to a query.
Step 3 :
Add WebMethods so that you can create users records in database. Use SqlCommand to fire INSERT queries on your database tables.
EDIT : Read here for a sample on how to write web services in VB.Net. And yes, you already know now, how to use SqlCommand to fire SQL queries, do the same for INSERT queries too.
Step 4 :
Create a WebMethod, that validates a user. For this, use SqlCommand object to fire your query written in Step 2. If you get a row as a result, the user is valid.
EDIT : Refer instructions to above steps and you should be able to create this on your own.
Hope I am clear enough.

Resources