How can I create a table from SQL Command that will have a ID that is auto-number or auto-increment?
SqlCommand com
= new SqlCommand("create table VeryCoolTable(\"Name\" nvarchar(50)
,id AUTONUMBER)", con);
The counter is not recognized and I get error.
if you are using SQL-Server it is called IDENTITY
ID int IDENTITY(1,1)
1. first argument is the starting value
2. second argument is incrementing count
if you want to start the value from 500 and increment it by 5
then try this:
ID int IDENTITY(500,5)
Solution 1:
SqlCommand com = new SqlCommand("create table VeryCoolTable(\"Name\"
nvarchar(50),ID int IDENTITY(1,1))", con);
Note: i would suggest you to declare the ID column as PRIMARY KEY to identify the records in your table uniqly.
Solution 2
SqlCommand com = new SqlCommand("create table VeryCoolTable(\"Name\"
nvarchar(50),ID int IDENTITY(1,1) PRIMARY KEY)", con);
CREATE TABLE Persons
(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Related
I want to use Windows Forms and C# to implement a Database application which consists of the following tables:
Student table:
CREATE TABLE [dbo].[Student]
(
[Id] INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[MyId] AS ('S' + RIGHT('00' + CONVERT([varchar](5), [Id]), (2))) PERSISTED,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Class table:
CREATE TABLE [dbo].[Class]
(
[Id] INT NOT NULL,
[Teacher] NVARCHAR(50) NOT NULL,
[Grade] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
StudentClassCombo:
CREATE TABLE [dbo].[StudentClassCombo]
(
[ClassID] INT NOT NULL,
[StudentID] INT NOT NULL,
CONSTRAINT [ClassFK]
FOREIGN KEY ([ClassID]) REFERENCES [dbo].[Class] ([Id]),
CONSTRAINT [StudentFK]
FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student] ([Id])
);
I have a Windows forms interface through which I can assign students to classes.
I want to ensure that when the a student that has already been assigned to a class is re-assigned to a different class. the previous student-class assignment should be overwritten with the new one. In the case above, if Student ID 1 is already assigned to Class ID 1. But if the user decides to re-assign Student ID 1 to Class ID 2, the existing StudentClassCombo entry of 1-1 should be changed to 1-2.
I have written the following code to perform this update but I am encountering an exception:
string UpdateQuery = #"UPDATE dbo.StudentClassCombo SET"
+ " Class.ID as ClassId, Student.Id as StudentId FROM dbo.Class, dbo.Student" +
" WHERE Class.Grade=#Grade and Student.Name LIKE #StudentName";
using (connection = new SqlConnection(connectionString))
using (SqlCommand Insertcmd = new SqlCommand(UpdateQuery, connection))
{
connection.Open();
Insertcmd.Parameters.Add("#Grade", SqlDbType.Int);
Insertcmd.Parameters.Add("#StudentName", SqlDbType.NVarChar, 50);
foreach (ListViewItem eachItem in StudentsList.CheckedItems)
{
Insertcmd.Parameters["#Grade"].Value = int.Parse(ClassNames.Text);
Insertcmd.Parameters["#StudentName"].Value = eachItem.SubItems[1].Text.ToString();
Insertcmd.ExecuteNonQuery();
}
connection.Close();
}
The exception I am seeing now is as follows:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'as'.
How should I update the StudentClassCombo entries?
You should first executenonquery this:
UPDATE StudentClassCombo SET ClassId = #ClassId WHERE StudentId =#StudentId
..and capture the return value from ExecuteNonQuery
If the return value is 0, no records were updated (there is no student with that ID), run the following insert instead:
INSERT StudentClassCombo (ClassId,StudentId) VALUES(#ClassId,#StudentId)
You seem to already know how to add parameters to sql commands etc so I'll skip that part
Put a unique index on StudentId
If Class:Student is 1:Many (as you imply) it would be more typical to put ClassId as a column of Student table than have a middleman table, unless that middle table stores other relevant data than just the class and student id
i want to see the data only with the invoice ID i enter so i tried this code to do that
Crystal_Bill cr = new Crystal_Bill();
SqlConnection conect = new SqlConnection("Data Source=DESKTOP-R34C6VV\\SQL;Initial Catalog=Restaurant;Integrated Security=True");
string sql = "Select * from Orders where InvoiceID='"+PrepareBill_txt1.Text+"'";
DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,conect);
adapter.Fill(dt,"Orders");
cr.SetDataSource(dt.Tables["Orders"]);
open.crystalReportViewer1.ReportSource = cr;
Print open = new Print();
open.SHow();
but it did not work i still get all the data in the database is there is a problem in these codes ? can anyone fix it ? thanks
this is my data base
CREATE TABLE [dbo].[Orders] (
[InvoiceID] INT NOT NULL,
[ItemNO] INT NOT NULL,
[Category] VARCHAR (50) NULL,
[ItemName] VARCHAR (50) NULL,
[Price] FLOAT (53) NULL,
[Qty] INT NOT NULL,
[SubTotal] FLOAT (53) NULL,
CONSTRAINT [Orders_FK1] FOREIGN KEY ([InvoiceID]) REFERENCES [dbo].[Invoice] ([InvoiceID])
);
As per your code you are passing invoice ID as a parameter value in your SQl Query, Your invoice ID has INT datatypes and you are trying to pass it with a single quote in your query so that consider invoice id as a varchar value. You can remove a single quote and try once again. that may help you.
i.g:
string sql = "Select * from Orders where InvoiceID="+ PrepareBill_txt1.Text +"";
I am working with C# and I want to insert some values to my SQL Server database, here is my data base definition:
CREATE TABLE [dbo].[Users]
(
[Id] INT NOT NULL IDENTITY (1,1) PRIMARY KEY DEFAULT 1000,
[FullName] VARCHAR(50) NULL,
[Pseudo] VARCHAR(50) NULL,
[Mail] VARCHAR(50) NULL,
[Password] VARCHAR(50) NULL,
[Organism] VARCHAR(50) NULL,
[RegistredAt] DATETIME NULL,
[Confirmed] INT NULL
)
and this how I am trying to insert the values to the database using C#:
SqlCommand command = new SqlCommand("INSERT INTO Users VALUES(#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)", con);
command.Parameters.AddWithValue("#FullName", FullName);
command.Parameters.AddWithValue("#Pseudo", Pseudo);
command.Parameters.AddWithValue("#Mail", Mail);
command.Parameters.AddWithValue("#Password", Password);
command.Parameters.AddWithValue("#Organism", Organism);
command.Parameters.AddWithValue("#RegistredAt", DateTime.Now);
command.Parameters.AddWithValue("#Confirmed", Confirmed);
con.Open();
int i = command.ExecuteNonQuery();
con.Close();
When I execute the code, the instruction command.ExecuteNonQuery(); returns an exception:
Column name or number of supplied values does not match table definition
Where is the error?
You might need to supply the column names in your query:
INSERT INTO Users (FullName, Pseudo, Mail, Password, Organism, RegistredAt, Confirmed)
VALUES (#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)
If you don't supply the column names, it assumes you want to use all columns, including the ID field. That's the reason for the error -- you're supplying 7 values for a table with 8 columns. Since you are using a subset, you need to specify them.
Also, I'm not sure if you are at a stage where it can be fixed, but you have a typo in "RegistredAt" -- it should be "RegisteredAt".
I want to take educational qualification records in my Asp.net form. As I have to take the record of class 10th, 12th, graduation, master. So I have created four rows for this... and 5 columns (year of exam, board, percentage, total mark, division).
Now I want to insert all rows in database with one button click by maintaining the primary key common for one user in all four records.
Please help me with the code (C#)
You may want to look at using a Composite Primary Key. This is a Primary Key that uses multiple columns to compose a single key. There are arguments for and against this strategy. See: What are the pros and cons of using multi column primary keys?
As an example, if your table looks like this:
CREATE TABLE [dbo].[StudentExam]
(
[StudentId] INT NOT NULL PRIMARY KEY,
[Year] INT NOT NULL,
[Board] SOMEDATATYPE NOT NULL,
[Percentage] FLOAT NOT NULL,
[TotalMark] INT NOT NULL,
[Division] SOMEDATATYPE NOT NULL,
)
You can alter the schema to look like this instead:
CREATE TABLE [dbo].[StudentExam]
(
[StudentId] INT NOT NULL,
[Year] INT NOT NULL,
[Board] SOMEDATATYPE NOT NULL,
[Percentage] FLOAT NOT NULL,
[TotalMark] INT NOT NULL,
[Division] SOMEDATATYPE NOT NULL,
CONSTRAINT [PK_StudentExam] PRIMARY KEY ([StudentId], [Year])
)
By doing this, you are declaring that for any given row in this table, it is uniquely identified by the Student and Year together. You can still query on just the student, or just the year, but only together will they identify a row.
For more information on primary keys, see Create Primary Keys
Create Table Type in Sql
CREATE TYPE [dbo].[TypeName] AS TABLE(
[name1] [varchar](1000) NULL,
[name2] [varchar](1000) NULL,
[name3] [varchar](max) NULL
)
GO
Create Procedure in SQL :
ALTER PROCEDURE [dbo].[InsertData]
#TableType TypeName readonly
AS
INSERT INTO [dbo].[Table_Master]
(Tname1,Tname2,Tname3)
select name1,name2,name3 from #TableType
Then Go To Code Behind
OpenConnection();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = spName;
sqlcmd.Connection = sqlconn;
SqlParameter tvpParam = sqlcmd.Parameters.AddWithValue("#Type", Your
Datatable);
tvpParam.SqlDbType = SqlDbType.Structured;
SqlParameter returnParameter = sqlcmd.Parameters.Add("RetVal",
SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlcmd.ExecuteNonQuery();
int Result = (int)returnParameter.Value;
sqlcmd.Dispose();
return Result;
Pass your DT in Uper Code...It Will Work Completely
I am trying to get company id like "Cp-00001". If data exists in table then the id should be "Cp-00001" + 1 = "Cp=00002" and do on...
Here's what I have so far:
CREATE PROCEDURE [dbo].[sp_AutoGenerateCustomerCode]
AS
DECLARE #id VARCHAR(10)
BEGIN
SELECT #id = 'Cp-' + CAST(MAX(CAST(SUBSTRING(CompanyCode,4,5) AS INTEGER))+1 AS VARCHAR) FROM [Beauty Saloon Project].[dbo].[tbl_Company];
IF #id IS NULL
BEGIN
SET #id = 'Cp-00001';
END
RETURN #id;
END
but when i call it here
datatable DT = new datatable
DT = ExecuteSpDataTable("sp_AutoGenerateCustomerCode");
This returns null.
If I don't have data then it should return Cp-00001, but I have one data row in which company code is saloon is it the reason for null ???
EDIT:
public DataTable ExecuteSpDataTable(string SPName)
{
try
{
if (ConnectionOpen())
{
SqlCommand objSqlCommand = new SqlCommand(SPName, objConnection);
objSqlCommand.CommandType = CommandType.StoredProcedure;
objSqlCommand.CommandTimeout = 10000;
SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter();
DataTable objDataTable = new DataTable();
objSqlDataAdapter.SelectCommand = objSqlCommand;
objSqlDataAdapter.Fill(objDataTable);
ConnectionClose();
return objDataTable;
}
return null;
}
catch (Exception ex)
{
objErrorLogs.LogError(ex);
return null;
}
}
One word of advice: DON'T DO THIS! Using this SELECT MAX() + 1 approach is not safe under load, as soon as more than one user will be using your application, you WILL HAVE DUPLICATES - sooner or later.
The only viable solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblCompany
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS 'CP-' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:
INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and CompanyID will contain values like CP-00001, CP-00002,...... and so on - automatically, safely, reliably, no duplicates.
Update: if you want to make the CompanyID the primary key, you could use this T-SQL statement:
CREATE TABLE dbo.tblCompany
(ID INT IDENTITY(1,1) NOT NULL,
CompanyID AS 'CP-' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED
CONSTRAINT PK_tblCompany PRIMARY KEY NONCLUSTERED,
.... your other columns here....
)
CREATE CLUSTERED INDEX CIX_Company ON dbo.tblCompany(ID);
I would leave the clustered index on ID and just move the primary key constraint to use CompanyID instead.