I have this SqlCommandProvider:
type Insert_NewFeed =
SqlCommandProvider<
"
INSERT INTO info.LiveFeed
( Id ,
MediaId ,
FactTypeId ,
Price ,
Description ,
PhoneNumber ,
Email ,
Website ,
CreateDate ,
CityId
)
VALUES ( #id , -- Id - nvarchar(128)
#mediaId , -- MediaId - nvarchar(128)
#factTypeId , -- FactTypeId - int
#price , -- Price - decimal
#description , -- Description - nvarchar(max)
#phoneNumber , -- PhoneNumber - nvarchar(50)
#email , -- Email - nvarchar(max)
#website , -- Website - nvarchar(max)
#createDate , -- CreateDate - datetime2
#cityId -- CityId - int
)
", Admin.connectionString, ConfigFile = "Web.config">
When I call it and try to pass null for the price column, which accepts a null in the database, I get an error. Is this possible?
Table definition:
[Id] [nvarchar](128) NOT NULL,
[MediaId] [nvarchar](128) NOT NULL,
[FactTypeId] [int] NOT NULL,
[Price] [decimal](18, 2) NULL,
[Description] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](50) NULL,
[Email] [nvarchar](max) NULL,
[Website] [nvarchar](max) NULL,
[CreateDate] [datetime2](7) NOT NULL,
[CityId] [int] NULL
As per Dimitry Sevastianov's comment, here is the solution.
First, assigned true to the parameter AllParametersOptional:
type Insert_NewFeed =
SqlCommandProvider<
"
INSERT INTO info.LiveFeed
( Id ,
MediaId ,
FactTypeId ,
Price ,
Description ,
PhoneNumber ,
Email ,
Website ,
CreateDate ,
CityId
)
VALUES ( #id , -- Id - nvarchar(128)
#mediaId , -- MediaId - nvarchar(128)
#factTypeId , -- FactTypeId - int
#price , -- Price - decimal
#description , -- Description - nvarchar(max)
#phoneNumber , -- PhoneNumber - nvarchar(50)
#email , -- Email - nvarchar(max)
#website , -- Website - nvarchar(max)
#createDate , -- CreateDate - datetime2
#cityId -- CityId - int
)
", Admin.connectionString, ConfigFile = "Web.config"
, AllParametersOptional = true>
Next, make call such as this:
let rowResult = (new Insert_NewFeed())
.Execute(Some fC.Id, Some fC.MediaId, Some fC.FactTyeId,
None,
Some fC.Description, Some fC.PhoneNumber, Some fC.Email,
Some fC.Website, Some fC.CreateDate, Some fC.CityId)
Related
I want to search pattern in file from "COMPRESS" till ")" and comment it.
My input file as below :
CREATE MULTISET TABLE TESTDB.testTbl ,FALLBACK ,
(
Local_Pd BIGINT NOT NULL,
Year_Id INTEGER NOT NULL,
par_t CHAR(15) CHARACTER SET LATIN NOT CASESPECIFIC,
PB_Ind INTEGER COMPRESS(0,1,2,3,4,5,6,6))
UNIQUE PRIMARY INDEX ( Local_Pd ,Year_Id ,par_t,
PB_Ind);
Output file :
CREATE MULTISET TABLE TESTDB.testTbl ,FALLBACK ,
(
Local_Pd BIGINT NOT NULL,
Year_Id INTEGER NOT NULL,
par_t CHAR(15) CHARACTER SET LATIN NOT CASESPECIFIC,
PB_Ind INTEGER /* COMPRESS(0,1,2,3,4,5,6,6) */ )
UNIQUE PRIMARY INDEX ( Local_Pd ,Year_Id ,par_t,
PB_Ind);
Something like this should work
import re
test_str = "CREATE MULTISET TABLE TESTDB.testTbl ,FALLBACK , ( Local_Pd BIGINT NOT NULL, Year_Id INTEGER NOT NULL, par_t CHAR(15) CHARACTER SET LATIN NOT CASESPECIFIC, PB_Ind INTEGER COMPRESS(0,1,2,3,4,5,6,6)) UNIQUE PRIMARY INDEX ( Local_Pd ,Year_Id ,par_t, PB_Ind);"
regex = r"(COMPRESS\([^\)]*\))"
t=re.sub(regex, r"/* \1 */", test_str)
print(t)
I have the following code:
var statList = (from i in _dbContext.Screenshots
where EntityFunctions.TruncateTime(i.dateTimeServer.Value) >= startDate && EntityFunctions.TruncateTime(i.dateTimeServer.Value) <= endDate
group i by EntityFunctions.TruncateTime(i.dateTimeServer.Value)
into g
select new ScreenshotStatistic()
{
Date = g.Key.Value,
AllScreenshots = g.Count(),
ScreenshotsNoSilent = g.Where(p => p.version.IndexOf("silent") == 0).Count(),
ScreenshotsNoSilentWithViews = g.Where(p => p.version.IndexOf("silent") == 0 && p.viewsPage + p.viewsOriginal > 0).Count(),
ScreenshotsOnlySilent = g.Where(p => p.version.IndexOf("silent") >= 0).Count(),
ScreenshotsOnlySilentWithViews = g.Where(p => p.version.IndexOf("silent") >= 0 && p.viewsPage + p.viewsOriginal > 0).Count(),
ScreenshotsOnlyUploadViaSite = g.Where(p => p.version.IndexOf("UPLOAD_VIA_SITE") >= 0).Count(),
ScreenshotsOnlyUploadViaSiteWithViews = g.Where(p => p.version.IndexOf("UPLOAD_VIA_SITE") >= 0 && p.viewsPage + p.viewsOriginal > 0).Count()
}).ToList();
It works carefully for my local database, but I get "Operation timeout" when I try to connect to SQL Azure. As I understand, my request is not optimized. How can I do the request better?
table has the following structure:
CREATE TABLE [dbo].[Screenshots](
[id] [int] IDENTITY(1,1) NOT NULL,
[dateTimeClient] [datetime] NOT NULL,
[name] [nvarchar](500) NOT NULL,
[username] [varchar](50) NULL,
[filename] [nvarchar](50) NULL,
[description] [nvarchar](500) NULL,
[version] [varchar](50) NULL,
[lang] [varchar](50) NULL,
[dateTimeServer] [datetime] NULL CONSTRAINT [DF_Screenshots_dateTimeServer] DEFAULT (getdate()),
[isPublic] [bit] NOT NULL CONSTRAINT [DF_Screenshots_isPublic] DEFAULT ((0)),
[viewsPage] [int] NOT NULL CONSTRAINT [DF_Screenshots_viewsPage_1] DEFAULT ((0)),
[viewsThumb] [int] NOT NULL CONSTRAINT [DF_Screenshots_viewsThumb_1] DEFAULT ((0)),
[viewsOriginal] [int] NOT NULL CONSTRAINT [DF_Screenshots_viewsOriginal_1] DEFAULT ((0)),
[statusID] [int] NOT NULL,
CONSTRAINT [PK_Screenshots] 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
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Screenshots] WITH CHECK ADD CONSTRAINT [FK_Screenshots_ScreenshotStatuses] FOREIGN KEY([statusID])
REFERENCES [dbo].[ScreenshotStatuses] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Screenshots] CHECK CONSTRAINT [FK_Screenshots_ScreenshotStatuses]
GO
EntityFunctions.TruncateTime is being translated into:
convert (datetime2, convert(varchar(255), [dateTimeServer], 102) , 102)
This is causing your query to be non-sargable, resulting in slow performance and timeout. I recommend making the following changes
First off, I do not see why you need to truncate the time in your where clause. I suggest you make this change:
where i.dateTimeServer.Value >= startDate && i.dateTimeServer.Value <= endDate
This will prevent the database from having to run the function on every record.
If the query still times out, I would change the group by to:
group i by new {
i.dateTimeServer.Value.Year,
i.dateTimeServer.Value.Month,
i.dateTimeServer.Value.Day
}
Functionally this is the same, but I believe it produces a more friendly translation:
DATEPART (year, dateTimeServer), DATEPART (month, dateTimeServer) etc..
Add an index to dateTimeServer
If all else fails, you will need to add a column to your table with the time portion truncated. Index it and use it in your query.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to SQLBulkCopy “insert or update if exists”?
I am using SQLBulkCopy to insert Bulk records
How can I perform on update (rather than an insert) on records that already exist? Is this possible with SQLBulkCopy?
This is my code for SQLBulkCopy
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.BatchSize = CustomerList.Count;
bulkCopy.DestinationTableName = "dbo.tCustomers";
bulkCopy.ColumnMappings.Clear();
bulkCopy.ColumnMappings.Add("CustomerID", "CustomerID");
bulkCopy.ColumnMappings.Add("FirstName", "FirstName");
bulkCopy.ColumnMappings.Add("LastName", "LastName");
bulkCopy.ColumnMappings.Add("Address1", "Address1");
bulkCopy.ColumnMappings.Add("Address2", "Address2");
bulkCopy.WriteToServer(CustomerList);
}
Application Details
ASP.net MVC 3.0 Razor view Engine
SQL Server 2008
Thanks to #pst
with his suggestions this is how I implemented, if anyone has to implement similar.
Bulk Insert in to permanent Temp Table
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.BatchSize = CustomerList.Count;
bulkCopy.DestinationTableName = "dbo.tPermanentTempTable";
bulkCopy.ColumnMappings.Clear();
bulkCopy.ColumnMappings.Add("CustomerID", "CustomerID");
bulkCopy.ColumnMappings.Add("FirstName", "FirstName");
bulkCopy.ColumnMappings.Add("LastName", "LastName");
bulkCopy.ColumnMappings.Add("Address1", "Address1");
bulkCopy.ColumnMappings.Add("Address2", "Address2");
bulkCopy.WriteToServer(CustomerList);
}
Then call a stored Procedure to Merge the temp table with actual table
using (Entities context = new Entities())
{
System.Nullable<int> iReturnValue = context.usp_Customer_BulkUploadMerge(customerid, locationID).SingleOrDefault();
if (iReturnValue.HasValue)
{
// return was successful!
}
}
This is how I used Merge in my Stored Procedure
ALTER PROCEDURE usp_Customer_BulkUploadMerge
(
#CustomerID INT ,
#locationID INT
)
AS
BEGIN
DECLARE #retValue INT
BEGIN TRY
IF OBJECT_ID('tCustomers') IS NOT NULL
BEGIN
BEGIN TRANSACTION MergPatientsTable
SET NOCOUNT ON;
MERGE dbo.tCustomers AS target
USING
( SELECT PU.CustomerID ,
PU.LocationID ,
PU.FirstName ,
PU.LastName ,
PU.MiddleInitial ,
PU.Gender ,
PU.DOB
FROM dbo.tPermanentTempTable PU
WHERE PU.CustomerID = #CustomerID
AND PU.LocationID = #locationID
GROUP BY PU.CustomerID ,
PU.LocationID ,
PU.FirstName ,
PU.LastName ,
PU.MiddleInitial ,
PU.Gender ,
PU.DOB
) AS source ( CustomerID, LocationID, FirstName,
LastName, MiddleInitial, Gender, DOB )
ON ( LOWER(target.FirstName) = LOWER(source.FirstName)
AND LOWER(target.LastName) = LOWER(source.LastName)
AND target.DOB = source.DOB
)
WHEN MATCHED
THEN
UPDATE SET
MiddleInitial = source.MiddleInitial ,
Gender = source.Gender,
LastActive = GETDATE()
WHEN NOT MATCHED
THEN
INSERT (
CustomerID ,
LocationID ,
FirstName ,
LastName ,
MiddleInitial ,
Gender ,
DOB ,
DateEntered ,
LastActive
) VALUES
( source.CustomerID ,
source.LocationID ,
source.FirstName ,
source.LastName ,
source.MiddleInitial ,
source.Gender ,
source.DOB ,
GETDATE() ,
NULL
);
DELETE PU
FROM dbo.tPermanentTempTable PU
WHERE PU.CustomerID = #CustomerID
AND PU.LocationID = #locationID
COMMIT TRANSACTION MergPatientsTable
SET #retValue = 1
SELECT #retValue
END
ELSE
BEGIN
SET #retValue = -1
SELECT #retValue
END
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION MergPatientsTable
DECLARE #ErrorMsg VARCHAR(MAX);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
SET #ErrorMsg = ERROR_MESSAGE();
SET #ErrorSeverity = ERROR_SEVERITY();
SET #ErrorState = ERROR_STATE();
SET #retValue = 0
SELECT #retValue
-- SELECT 0 AS isSuccess
END CATCH
END
I am trying to use CASE in a SQL Select statement that will allow me to get results where I can utilize the length of one string to produce the resutls of another string. These are for non-matched records from two data sets that share a common ID, but variant Data Source.
Case statement is below:
Select Column1, Column2,
Case
When Column1 = 'Something" and Len(Column2) = '35' Then Column1 = "Something Else" and substring(Column2, 1, 35)
End as Column3
From dbo.xxx
When I run it I get the following error:
Msg 102, Level 15, State 1, Line 5 Incorrect syntax near '='.
You need to have a value for each WHEN, and ought to have an ELSE:
Select Data_Source, CustomerID,
CASE
WHEN Data_Source = 'Test1' and Len(CustomerName) = 35 THEN 'First Value'
WHEN Data_Source = 'Test2' THEN substring(CustomerName, 1, 35)
ELSE 'Sorry, no match.'
END AS CustomerName
From dbo.xx
FYI: Len() doesn't return a string.
EDIT:
A SQL Server answer that addresses some of the comments might be:
declare #DataSource as Table ( Id Int Identity, CustomerName VarChar(64) )
declare #VariantDataSource as Table ( Id Int Identity, CostumerName VarChar(64) )
insert into #DataSource ( CustomerName ) values ( 'Alice B.' ), ( 'Bob C.' ), ( 'Charles D.' )
insert into #VariantDataSource ( CostumerName ) values ( 'Blush' ), ( 'Dye' ), ( 'Pancake Base' )
select *,
-- Output the CostumerName padded or trimmed to the same length as CustomerName. NULLs are not handled gracefully.
Substring( CostumerName + Replicate( '.', Len( CustomerName ) ), 1, Len( CustomerName ) ) as Clustermere,
-- Output the CostumerName padded or trimmed to the same length as CustomerName. NULLs in CustomerName are explicitly handled.
case
when CustomerName is NULL then ''
when Len( CustomerName ) > Len( CostumerName ) then Substring( CostumerName, 1, Len( CustomerName ) )
else Substring( CostumerName + Replicate( '.', Len( CustomerName ) ), 1, Len( CustomerName ) )
end as 'Crustymore'
from #DataSource as DS inner join
#VariantDataSource as VDS on VDS.Id = DS.Id
Select
Column1,
Column2,
Case
When Column1 = 'Something' and Len(Column2) = 35
Then 'Something Else' + substring(Column2, 1, 35)
End as Column3
From dbo.xxx
Update your query on
use '+' for string concat
len() returns int, no need to use ''
remove "Column1 =" in the case when condition
replace "" with ''
Hope this help.
IS there anyway i can improve this query?
SELECT DISTINCT adb_product_type.strproduct_type AS strproduct_type, adb_product_cat.strproduct_cat AS strproduct_cat, adb_product.strproduct AS strproduct,
CASE #campaignCount:=
(SELECT COUNT(DISTINCT adb_campaign_1.campaign_id)
FROM adb_camp_media AS adb_camp_media_1
LEFT JOIN adb_campaign AS adb_campaign_1 ON adb_campaign_1.campaign_id = adb_camp_media_1.campaign_id
LEFT JOIN adb_camp_media_prod AS adb_camp_media_prod_1 ON adb_camp_media_prod_1.media_num = adb_camp_media_1.media_num
WHERE
(adb_camp_media_1.inttotal_per_store = 1 AND adb_camp_media_1.lngproduct = adb_product.lngproduct OR adb_camp_media_1.inttotal_per_store > 1 AND adb_camp_media_prod_1.lngproduct = adb_product.lngproduct)
AND (
(
adb_campaign_1.start_date
BETWEEN '2011-01-01'
AND '2011-01-31'
)
OR (
adb_campaign_1.end_date
BETWEEN '2011-01-01'
AND '2011-01-31'
)
OR (
adb_campaign_1.start_date < '2011-01-01'
AND adb_campaign_1.end_date > '2011-01-31'
)
)
)
WHEN 0 THEN 'No' ELSE 'Yes' END AS 'YesNo',
CASE #campaignCount WHEN 0 THEN '' ELSE #campaignCount END AS 'CampaignCount',
CASE #campaignCount WHEN 0 THEN '' ELSE
(SELECT GROUP_CONCAT(DISTINCT adb_media_1.name ORDER BY adb_media_1.name SEPARATOR ', ' )
FROM adb_camp_media AS adb_camp_media_1
LEFT JOIN adb_campaign AS adb_campaign_1 ON adb_campaign_1.campaign_id = adb_camp_media_1.campaign_id
LEFT JOIN adb_camp_media_prod AS adb_camp_media_prod_1 ON adb_camp_media_prod_1.media_num = adb_camp_media_1.media_num
LEFT JOIN adb_media AS adb_media_1 ON adb_media_1.media_id = adb_camp_media_1.media_id
WHERE
(adb_camp_media_1.inttotal_per_store = 1 AND adb_camp_media_1.lngproduct = adb_product.lngproduct OR adb_camp_media_1.inttotal_per_store > 1 AND adb_camp_media_prod_1.lngproduct = adb_product.lngproduct)
AND (
(
adb_campaign_1.start_date
BETWEEN '2011-01-01'
AND '2011-01-31'
)
OR (
adb_campaign_1.end_date
BETWEEN '2011-01-01'
AND '2011-01-31'
)
OR (
adb_campaign_1.start_date < '2011-01-01'
AND adb_campaign_1.end_date > '2011-01-31'
)
)
)
END AS mediaName , adb_product.lngproduct
FROM adb_product_type
LEFT JOIN adb_product_cat ON adb_product_cat.lngproduct_type = adb_product_type.lngproduct_type
LEFT JOIN adb_product ON adb_product.lngproduct_cat = adb_product_cat.lngproduct_cat
LEFT JOIN adb_camp_media ON adb_camp_media.lngproduct = adb_product.lngproduct
LEFT JOIN adb_media ON adb_media.media_id = adb_camp_media.media_id
LEFT JOIN adb_camp_media_prod ON adb_camp_media_prod.media_num = adb_camp_media.media_num
LEFT JOIN adb_campaign ON adb_campaign.campaign_id = adb_camp_media.campaign_id
WHERE 1=1
ORDER BY YesNo DESC , strproduct_type, strproduct_cat, strproduct
TABLE STRUCTURE
-- Table structure for table adb_camp_media
CREATE TABLE adb_camp_media (
media_num int(11) NOT NULL auto_increment,
campaign_id int(11) NOT NULL default '0',
media_id int(11) NOT NULL default '0',
inttotal_per_store int(4) NOT NULL default '0',
units_per_item int(2) default NULL,
lngproduct int(11) NOT NULL default '0',
rental_cost double(10,2) default NULL,
checkers_rental double default NULL,
hyper_rental double default NULL,
usave_rental double default NULL,
ls_rental double(10,2) default '0.00',
spar_rental double(10,2) default '0.00',
backboard tinyint(1) NOT NULL,
PRIMARY KEY (media_num),
KEY campaign_id (campaign_id,media_id,lngproduct),
KEY lngproduct (lngproduct)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table adb_camp_media_prod
CREATE TABLE adb_camp_media_prod (
media_prod_id int(11) NOT NULL auto_increment,
media_num int(4) NOT NULL,
lngproduct int(4) NOT NULL,
PRIMARY KEY (media_prod_id),
KEY media_num (media_num,lngproduct),
KEY lngproduct (lngproduct)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table adb_campaign
CREATE TABLE adb_campaign (
campaign_id int(11) NOT NULL auto_increment,
client_id int(11) NOT NULL default '0',
campaign_name varchar(50) NOT NULL default '',
description text,
position_desc text,
start_date date NOT NULL default '0000-00-00',
end_date date NOT NULL default '0000-00-00',
approved tinyint(1) NOT NULL default '0',
created_date date NOT NULL default '0000-00-00',
updated_date datetime default NULL,
user_id int(11) NOT NULL default '0',
pinno varchar(50) NOT NULL default '',
jobno varchar(30) NOT NULL default '',
quoteno varchar(30) NOT NULL default '',
sales_ae_id int(11) default NULL,
artwork_specno varchar(30) NOT NULL default '',
artwork_jobno varchar(30) NOT NULL default '',
agency tinyint(1) NOT NULL default '0',
brand_name varchar(50) NOT NULL default '',
paypercycle tinyint(1) NOT NULL default '0',
agency_comm double default NULL,
variant varchar(100) default NULL,
pack_size varchar(100) default NULL,
discount double default NULL,
discount_val double default NULL,
sales_comm double NOT NULL default '0',
cancelled tinyint(1) default '0',
onhold tinyint(1) default '0',
campaign_status_id int(4) default NULL,
PRIMARY KEY (campaign_id),
UNIQUE KEY jobno (jobno),
KEY start_date (start_date),
KEY end_date (end_date),
KEY campaign_name (campaign_name),
KEY user_id (user_id,cancelled,onhold)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table adb_product
CREATE TABLE adb_product (
lngproduct int(11) NOT NULL auto_increment,
strproduct varchar(100) NOT NULL default '',
lngproduct_cat int(11) NOT NULL default '0',
PRIMARY KEY (lngproduct),
KEY lngproduct_cat (lngproduct_cat)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table adb_product_cat
CREATE TABLE adb_product_cat (
lngproduct_cat int(11) NOT NULL auto_increment,
strproduct_cat varchar(100) NOT NULL default '',
lngproduct_type int(11) NOT NULL default '0',
PRIMARY KEY (lngproduct_cat),
KEY lngproduct_type (lngproduct_type)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table adb_product_type
CREATE TABLE adb_product_type (
lngproduct_type int(11) NOT NULL auto_increment,
strproduct_type varchar(100) NOT NULL default '',
PRIMARY KEY (lngproduct_type)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;