Search By Invoice ID in crystal reports - c#

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 +"";

Related

How to insert multiple rows of one user with common ID (primary key) into SQL Server database?

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

Cannot convert datatype nvarchar to numeric

I import data from from an Excel file into a SQL Server database with the following query. The Excel file has all values as string types (' before every cells).
I get this error when I import it."Cannot convert datatype nvarchar to numeric"
If I remove the two columns SalePrice and Price2 from importing, then the import is successful.
The datatypes of my table is
CREATE TYPE [dbo].[InventoryType] AS TABLE
(
[LocalSKU] [varchar](200) NOT NULL,
[ItemName] [varchar](200) NULL,
[QOH] [int] NULL,
[Price] [decimal](19, 4) NULL,
[Discontinued] [bit] NULL,
[Barcode] [varchar](25) NULL,
[Integer2] [int] NULL,
[Integer3] [int] NULL,
[SalePrice] [decimal](19, 4) NULL,
[SaleOn] [bit] NULL,
[Price2] [decimal](19, 4) NULL
)
GO
The query I am using is:
SqlCommand sqlcmd = new SqlCommand
(#"MERGE Inventory AS target
USING (SELECT
LocalSKU, ItemName, QOH, Price, Discontinued,
Barcode, Integer2, Integer3, SalePrice, SaleOn, Price2
FROM #source) AS Source ON (Source.LocalSKU = target.LocalSKU)
WHEN MATCHED THEN
UPDATE
SET ItemName = source.ItemName,
Price = source.Price,
Discontinued = source.Discontinued,
Barcode = source.Barcode,
Integer2 = source.Integer2,
Integer3 = source.QOH,
SalePrice = source.SalePrice,
SaleOn = source.SaleOn,
Price2 = source.Price2;", sqlconn);
SqlParameter param;
param = sqlcmd.Parameters.AddWithValue("#source", dr);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.InventoryType";
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
One thing to keep in mind is that you may have some invalid data in the given column that's throwing the error(s). For example if you have a Numeric column and have letters or inproperly formatted numeric values, this error will be thrown. Check for values in your cells that aren't correct first. This includes trailing or leading spaces as well.

C# SQL create table with autonumber column

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)
)

Temporary table or Truncate fix table?

I have 5 fields obtained form two tables to insert into another table. Is it more efficient to do it with temporary table or with a fix table and truncate it each time I use it ?
If a temporary is more effective how to create within in c# a temporary table. Because this sql is not working ?
public static void CreateTempProd()
{
int result;
string sqlstr = "CREATE TEMPORARY TABLE ##tmptbl (id int NOT NULL AUTO_INCREMENT, dt DATETIME NOT NULL, qty int11 NOT NULL, rest int11 NOT NULL, nom VARCHAR(30) NOT NULL NOT NULL PRIMARY KEY id, ENGINE=MEMORY DEFAULT CHARSET=UTF8)";
MySqlConnection conn = new MySqlConnection(PublicVariables.cs);
MySqlCommand cmd = new MySqlCommand(sqlstr,conn);
MySqlTransaction trans;
conn.Open();
trans = conn.BeginTransaction();
try
{
result = cmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
trans.Rollback();
MessageBox.Show(e.ToString());
return;
}
trans.Commit();
}
Your SQL syntax is a bit off;
CREATE TEMPORARY TABLE ##tmptbl ( -- ## needs quoting
id int NOT NULL AUTO_INCREMENT,
dt DATETIME NOT NULL,
qty int11 NOT NULL, -- int11 should be int(11)
rest int11 NOT NULL, -- int11 should be int(11)
nom VARCHAR(30) NOT NULL NOT NULL -- double NOT NULL
PRIMARY KEY id, -- id needs braces
ENGINE=MEMORY DEFAULT CHARSET=UTF8 -- should go outside the table braces
)
That is, it should be something like...
CREATE TEMPORARY TABLE `##tmptbl` (
id int NOT NULL AUTO_INCREMENT,
dt DATETIME NOT NULL,
qty int(11) NOT NULL,
rest int(11) NOT NULL,
nom VARCHAR(30) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=MEMORY DEFAULT CHARSET=UTF8
A good idea is to just try running your exact query at the mysql command prompt, that would have caught this error and allowed you to fix it.

Auto Increment Id in stored procedure not working

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.

Categories

Resources