Filtering results between two dates with rdlc report in asp.net mvc - sql

I am using RDLC for reports loaded into ASP.NET MVC.
I tried to filter the results between two dates, but when I type the following query below I get the following error:
"the new command text returns data with schema different from the schema of the main query. Check your query's command text if this is not desired."
Can you help me on how to do it?
SELECT
SiparisKalems.SiparisKalemId,
SiparisKalems.Siparisid,
SiparisKalems.SiparisKalemTarih,
SiparisKalems.SiparisKalemAdet,
SiparisKalems.SiparisKalemFiyat,
SiparisKalems.SiparisKalemToplam,
SiparisKalems.Urunid,
Uruns.Urunid AS Expr1,
Uruns.UrunAdi,
Uruns.UrunFiyat,
Uruns.UrunGorsel,
Uruns.Kategoriid,
Uruns.Durum
FROM
SiparisKalems
INNER JOIN Uruns ON SiparisKalems.Urunid = Uruns.Urunid
WHERE
(
SiparisKalems.SiparisKalemTarih >= #Param1
AND
SiparisKalems.SiparisKalemTarih <= #Param2
)
ORDER BY
SiparisKalems.SiparisKalemTarih DESC
CREATE TABLE [dbo].[SiparisKalems](
[SiparisKalemId] [int] NOT NULL IDENTITY(1,1),
[Siparisid] [int] NOT NULL,
[SiparisKalemTarih] [datetime] NOT NULL,
[SiparisKalemAdet] [int] NOT NULL,
[SiparisKalemFiyat] [decimal](18, 2) NOT NULL,
[SiparisKalemToplam] [decimal](18, 2) NOT NULL,
[Urunid] [int] NOT NULL,
CONSTRAINT PK_dbo.SiparisKalems PRIMARY KEY CLUSTERED ( [SiparisKalemId] ),
CONSTRAINT FK_dbo.SiparisKalems_dbo.Siparislers_Siparisid ([Siparisid]) REFERENCES [dbo].[Siparislers] ([Siparisid]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.SiparisKalems_dbo.Uruns_Urunid] FOREIGN KEY([Urunid]) REFERENCES [dbo].[Uruns] ([Urunid]) ON DELETE CASCADE
)
CREATE TABLE [dbo].[Uruns](
[Urunid] [int] NOT NULL IDENTITY(1,1),
[UrunAdi] [varchar](30) NOT NULL,
[UrunFiyat] [decimal](18, 2) NOT NULL,
[UrunGorsel] [varchar](250) NOT NULL,
[Kategoriid] [int] NOT NULL,
[Durum] [bit] NOT NULL,
CONSTRAINT [PK_dbo.Uruns] PRIMARY KEY ( [Urunid] ),
CONSTRAINT [FK_dbo.Uruns_dbo.Kategoris_Kategoriid] FOREIGN KEY([Kategoriid]) REFERENCES [dbo].[Kategoris] ([Kategoriid]) ON DELETE CASCADE
)

Related

SQL Server: select records, not linked to another table

I have a table:
CREATE TABLE [dbo].[CollectionSite]
(
[SiteCode] [nvarchar](32) NOT NULL,
[AddressId] [int] NOT NULL,
[RemittanceId] [int] NULL,
// additional columns
)
and a linked table:
CREATE TABLE [dbo].[CollectionSiteAddress]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Address1] [nvarchar](255) NULL,
[Address2] [nvarchar](255) NULL,
[City] [nvarchar](128) NULL,
[State] [nvarchar](64) NULL,
[Zip] [nvarchar](32) NULL,
)
Relationship between these 2 tables:
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_AddressId]
FOREIGN KEY([AddressId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_RemittanceId]
FOREIGN KEY([RemittanceId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
I want to select all records from CollectionSiteAddress, which are not linked to CollectionSite (neither AddressId nor RemittanceId). Which request should I use?
I tried:
SELECT *
FROM CollectionSiteAddress
LEFT JOIN CollectionSite ON CollectionSiteAddress.Id = CollectionSite.AddressId
OR CollectionSiteAddress.Id = CollectionSite.RemittanceId
but it selects all records from CollectionSiteAddress
You are missing this WHERE clause:
WHERE CollectionSite.[SiteCode] IS NULL
because you want all the unmatched rows of CollectionSiteAddress.
I used the column [SiteCode] to check if it is NULL because it is not nullable in the definition of the table.
So you can write your query like this (shortened with aliases):
SELECT csa.*
FROM CollectionSiteAddress csa LEFT JOIN CollectionSite cs
ON csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
WHERE cs.[SiteCode] IS NULL
Or use NOT EXISTS:
SELECT csa.*
FROM CollectionSiteAddress csa
WHERE NOT EXISTS (
SELECT 1
FROM CollectionSite cs
WHERE csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
)

SQL Server partition and index

I have a requirement to design a table that is going to have around 80 million records. I created a partition for every month using persisted column (if its wrong suggest me the best way). Please find below scripts that I used to create tables and partition and the query that's going to be used often. Only Insertion and deletion will be done on this table.
-- Create the Partition Function
CREATE PARTITION FUNCTION PF_Invoice_item (int)
AS RANGE LEFT FOR VALUES (1,2,3,4,5,6,7,8,9,10,11,12);
-- Create the Partition Scheme
CREATE PARTITION SCHEME PS_Invoice_item
AS PARTITION PF_Invoice_item ALL TO ([Primary]);
CREATE TABLE [Invoice]
(
[invoice_id] [bigint] NOT NULL,
[Invoice_Number] [varchar](255) NULL,
[Invoice_Date] [date] NULL,
[Invoice_Total] [numeric](18, 2) NULL,
[Outstanding_Balance] [decimal](18, 2) NULL,
CONSTRAINT [PK_Invoice_id] PRIMARY KEY CLUSTERED([invoice_id] ASC)
)
CREATE TABLE [InvoiceItem](
[invoice_item_id] [bigint] NOT NULL,
[invoice_id] [bigint] NOT NULL,
[invoice_Date] [date] NULL,
[make] [varchar](255) NULL,
[serial_number] [varchar](255) NULL,
[asset_id] [varchar](100) NULL,
[application] [varchar](255) NULL,
[customer] [varchar](255) NULL,
[ucid] [varchar](255) NULL,
[dcn] [varchar](255) NULL,
[dcn_name] [varchar](255) NULL,
[device_serial_number] [varchar](255) NULL,
[subscription_name] [varchar](255) NULL,
[product_name] [varchar](255) NULL,
[subscription_start_date] [date] NULL,
[subscription_end_date] [date] NULL,
[duration] [varchar](50) NULL,
[promo_name] [varchar](255) NULL,
[promo_end_date] [date] NULL,
[discount] [decimal](18, 2) NULL,
[tax] [decimal](18, 2) NULL,
[line_item_total] [decimal](18, 2) NULL,
[mth] AS (datepart(month,[invoice_date])) PERSISTED NOT NULL,**
[RELATED_PRODUCT_RATEPLAN_NAME] [varchar](250) NULL,
[SUB_TOTAL] [decimal](18, 2) NULL,
[BILLING_START_DATE] [date] NULL,`enter code here`
[BILLING_END_DATE] [date] NULL,
[SUBSCRIPTION_ID] [varchar](200) NULL,
[DEVICE_TYPE] [varchar](200) NULL,
[BASE_OR_PROMO] [varchar](200) NULL,
CONSTRAINT [PK_InvoiceItem_ID] PRIMARY KEY CLUSTERED ([invoice_item_id]
ASC,[mth] ASC))
ON PS_Invoice_item(mth);
GO
ALTER TABLE [InvoiceItem] WITH CHECK ADD CONSTRAINT [FK_Invoice_ID]
FOREIGN KEY([invoice_id])
REFERENCES [Invoice] ([invoice_id])
GO
I will be using below queries
select subscription_name,duration,start_date,end_date,promotion_name,
promotion_end_date,sub_total,discount,tax,line_item_total from InvoiceItem
lt inner join Invoice on lt.invoice_id=invoice.invoice_id where
invoice.invoice_number='' and lt.customer='' and lt.ucid='' lt.make='' and
lt.SERIAL_NUMBER='' and lt.dcn='' and lt.application=''
select customer,make,application from billing.AssetApplicationTotals
lineItem inner join billing.Invoice invoice on
lineItem.invoice_id=invoice.invoice_id where invoice.invoice_number='';
SELECT [invoice_Date],[make],[serial_number],[application],[customer],
[ucid],[dcn],[dcn_name],[device_serial_number]
,[subscription_name],[product_name],[subscription_start_date],
[subscription_end_date],[duration],[promo_name],[promo_end_date]
FROM [InvoiceItem] where [application]=''
SELECT [invoice_Date],[make],[serial_number],[application],[customer],
[ucid],[dcn],[dcn_name],[device_serial_number]
,[subscription_name],[product_name],[subscription_start_date],
[subscription_end_date],[duration],[promo_name],[promo_end_date]
FROM [InvoiceItem] where [customer]=''
What is the best way to create index? Shall I create separate non clustered index for each filter, or shall I have Composite index and shall I have covering index to avoid key lookup?

How to assign 2 default values to SQL table column?

I am designing user registration table with below columns.
CREATE TABLE [dbo].[NCT_UserRegistration]
(
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL,
[User_Role] [varchar](20) NULL,
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
My requirement for the status and role as below.
status VARCHAR(15) Index, Enumeration of ENABLED, DISABLED.
role VARCHAR(20) Enumeration of SUPER_ADMIN and PROJECT_ADMIN
What I understood from above is status should take only Enabled or Disabled and same with role also. How can I design my table to make sure it takes only those two values? Also is there any way for example if I supply 1 then it is ENABLED and 0 for DISABLED.
May I get some ideas here? Any help would be appreciated. Thank you
You need to use CHECK CONSTRAINT to limit to specific values
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL CONSTRAINT chk_Status CHECK ([User_Status] IN ('ENABLED', 'DISABLED')),
[User_Role] [varchar](20) NULL CONSTRAINT chk_Role CHECK ([User_Role] IN ('SUPER_ADMIN','DISABLED')),
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
For enumeration you will have to handle at front end or while retriving values from table which is an extra step.
SELECT CASE WHEN [User_Status] = 1 THEN 'ENABLED' WHEN [User_Status] = 0 THEN 'DISABLED' END As UserStratus
FROM [dbo].[NCT_UserRegistration]
Can you try adding constraint as below for status field. If its working then apply the same to ROLE field.
alter table NCT_UserRegistration
add (STATUS VARCHAR(15) default 'ENABLED',
constraint conSTATUS check (STATUS in ('ENABLED', 'DISABLED')))
There are two possible approaches.
Check constraints - #mh2017 has explained this well in his answer.
Looking at the conversation that seems to fit your requirements better, but just for the sake of sharing idea, I will mention -
Foreign key constraint (FK)- If it is acceptable to modify the User_Status and User_Role columns to be of type tinyint (or similar number type), you can store just the ids in these and create enumeration (aka mapping tables) to store what the ids represent.
Create FK on User_Status and User_Role in NCT_UserRegistration to refer to the enumeration tables.
FKC ensures that the referring column (User_Status and User_Role in NCT_UserRegistration) cannot have value other than those listed in the referred to column (the respective id columns in the enumeration tables)
This Foreign key vs check constraint for integrity post also describes few benefits of using FK over check constraint
Here is a sample code showing foreign key approach
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] tinyint NULL, -- I changed this from varchar to tinyint
[User_Role] tinyint NULL, -- I changed this from varchar to tinyint
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
create table StatusEnumeration
(
StatusId tinyint,
Description varchar(10)
constraint pk_StatusEnumeration__StatusId primary key clustered (StatusId)
)
insert into StatusEnumeration(StatusId, Description)
values
(0, 'Disabled'),
(1, 'Enabled')
create table RoleEnumeration
(
RoleId tinyint,
Description varchar(20)
constraint pk_RoleEnumeration__RoleId primary key clustered (RoleId)
)
insert into RoleEnumeration(RoleId, Description)
values
(0, 'SUPER_ADMIN '),
(1, 'PROJECT_ADMIN')
alter table NCT_UserRegistration
add constraint fk_NCT_UserRegistration__StatusEnumeration_StatusId foreign key (User_Status)
references StatusEnumeration (StatusId)
go
alter table NCT_UserRegistration
add constraint fk_NCT_UserRegistration__RoleEnumeration_RoleId foreign key (User_Role)
references RoleEnumeration (RoleId)
go

Foreign key refers invalid column in referred table

I have a table ClientsPurchases with the column BillNo. I would like to refer BillNo column into Payments table as a Foreign Key, but its showing error.
There are no primary or candidate keys in the referred table.
'ClientsPurchases' that match the referencing column list in the
foreign key 'FK__Payments__BillNo__286302EC'. Msg 1750, Level 16,
State 0, Line 1
CREATE Table ClientsPurchases
(
PurchasesId int IDENTITY(1,1) PRIMARY KEY NOT NULL,
PurchasesDetails VARCHAR(75),
[BillNo] varchar(75) NULL
)
--My Payments table as bellow
CREATE TABLE [dbo].[Payments]
(
[PaymentId] [int] IDENTITY(1,1) NOT NULL,
[PayAmount] [decimal](18, 0) NULL,
[PaymentDate] [datetime] NULL,
[ClinetId] [int] NULL,
FOREIGN KEY ([BillNo]) REFERENCES ClientsPurchases(BillNo)
)
Please advice.
The [BillNo] in your ClientsPurchases should be unique.
Also, I think your foreign key should be defined as a column in the Payments table as well:
CREATE TABLE [dbo].[Payments]
(
[PaymentId] [int] IDENTITY(1,1) NOT NULL,
[PayAmount] [decimal](18, 0) NULL,
[PaymentDate] [datetime] NULL,
[ClinetId] [int] NULL,
[BillNo] [int] NOT NULL,
FOREIGN KEY ([BillNo]) REFERENCES ClientsPurchases(BillNo)
)
More about creating foreign key constraints here.
You cannot refer to BillNo because it isn't a key. You should make it NOT NULL and UNIQUE.

SQL unique column based on other columns

I have a SQL Server database table that I am trying to fix without having to resort to using the front end code to determine if the name of the institute is unique. I am setting up a Linq to SQL code base for all of the inserts.
here is the new table that I am trying to setup:
CREATE TABLE [dbo].[institution]
(
[institutionID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[typeID] [tinyint] NOT NULL REFERENCES [dbo].[institutiontype]([institutiontypeID]),
[name] [varchar](255) NOT NULL UNIQUE,
[cityID] [int] NULL REFERENCES [dbo].[city]([cityID]),
[stateID] [int] NULL REFERENCES [dbo].[stateprovince]([stateID]),
[countryID] [int] NULL REFERENCES [dbo].[country]([countryID]),
[createby] [int] NOT NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[createdatetime] [datetime] NOT NULL DEFAULT (GETDATE()),
[modifyby] [int] NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[modifydatetime] [datetime] NULL,
[dataversion] [int] NOT NULL DEFAULT (0)
)
The issue is, the institutionname needs to be unique ONLY when the cityID, stateID and the countryID are the same. Setting up the table with the institutename as unique will not satisfy the needs since there are times when the same name can exist in different, cities, states or countries.
How would I resolve this
You need to write a complex constraint in your table. Define a user-defined-function which returns true (1 in BIT) if your required condition is satisfied and false otherwise.
Put this constraint in the table schema with a CHECK constraint.
CREATE FUNCTION dbo.fnIsNameUnique (
#name [varchar](255),
#cityID int,
#stateID int,
#countryID int,
)
RETURNS tinyint
AS
BEGIN
DECLARE #Result tinyint
IF EXISTS(SELECT * FROM institution WHERE name = #name AND cityID = #cityID AND stateID = #stateID AND countryID = #countryID)
SET #Result= 0
ELSE
SET #Result= 1
RETURN #Result
END
CREATE TABLE [dbo].[institution]
(
[institutionID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[typeID] [tinyint] NOT NULL REFERENCES [dbo].[institutiontype]([institutiontypeID]),
[name] [varchar](255) NOT NULL UNIQUE,
[cityID] [int] NULL REFERENCES [dbo].[city]([cityID]),
[stateID] [int] NULL REFERENCES [dbo].[stateprovince]([stateID]),
[countryID] [int] NULL REFERENCES [dbo].[country]([countryID]),
[createby] [int] NOT NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[createdatetime] [datetime] NOT NULL DEFAULT (GETDATE()),
[modifyby] [int] NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[modifydatetime] [datetime] NULL,
[dataversion] [int] NOT NULL DEFAULT (0),
CONSTRAINT ckValidName CHECK (
dbo.fnIsNameUnique(name, cityID, stateID, countryID) = 1)
)
)
I don't know why you need anything so complex, just putting a UNIQUE constraint or index on ([name], CityID, StateID, CountryID) does what you say you need.