My SQL code that works running on the server.
SELECT
[LINE_NO], [CUST_ORDER_ID], [PART_ID],
[CUSTOMER_PART_ID], [MISC_REFERENCE], [PROMISE_DATE],
[PROMISE_DEL_DATE]
FROM
[CUST_ORDER_LINE]
WHERE
([CUST_ORDER_ID] = '33742-1'
AND [PROMISE_DATE] IS NULL
AND [PROMISE_DEL_DATE] IS NULL)
My asp.net code.
SelectCommand = "SELECT [LINE_NO], [CUST_ORDER_ID], [PART_ID], [CUSTOMER_PART_ID], [MISC_REFERENCE], [PROMISE_DATE], [PROMISE_DEL_DATE] FROM [CUST_ORDER_LINE] WHERE ([CUST_ORDER_ID] = ? AND [PROMISE_DATE] = ? AND [PROMISE_DEL_DATE] = ?)"
I'm using 3 query string parameters. The promise date and promise delivery date can be null. But when those values are null it returns no records.
How can I program this to change the SQL to 'is null' instead of = ''.
I think this is what you want:
Param 1 = OrderID
Param 2/3 are both Promise Date
Param 4/5 are both Promise Delivery Date
Code:
SelectCommand = "SELECT [LINE_NO], [CUST_ORDER_ID], [PART_ID], [CUSTOMER_PART_ID], [MISC_REFERENCE], [PROMISE_DATE], [PROMISE_DEL_DATE] FROM [CUST_ORDER_LINE] WHERE [CUST_ORDER_ID] = ? AND (? IS NULL OR [PROMISE_DATE] = ?) AND (? IS NULL OR [PROMISE_DEL_DATE] = ?)"
The SQL would be:
DECLARE #P1 INT, #P2 DATETIME, #P3 DATETIME
SELECT [LINE_NO], [CUST_ORDER_ID], [PART_ID], [CUSTOMER_PART_ID], [MISC_REFERENCE], [PROMISE_DATE], [PROMISE_DEL_DATE]
FROM [CUST_ORDER_LINE]
WHERE [CUST_ORDER_ID] = #P1
AND (#P2 IS NULL OR [PROMISE_DATE] = #P2)
AND (#P3 IS NULL OR [PROMISE_DEL_DATE] = #P3)
Related
I am using the below query and companyname is encrypted in table4. I have enabled the column encryption setting in web config. But it throws error while executing the below query.
var companyname = (from user in testEntities.table1
where user.email == "test#gmail.com"
join mapper in testEntities.table2 on customerId equals mapper.CustomerId into details
from company in details.DefaultIfEmpty()
join type in testEntities.table3 on user.CustomerTypeId equals type.Id
join companycategory in testEntities.table4 on company.CompanyId equals companycategory.CompanyId into cateogryname
from companyname in cateogryname.DefaultIfEmpty()
select (companyname.CompanyName == null || company.IsActive == false) ? type.Type : companyname.CompanyName).FirstOrDefault();
Error
Operand type clash: varchar is incompatible with nvarchar(100) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_....', column_encryption_key_name = 'keyname', column_encryption_key_database_name = 'testdb')\r\nStatement(s) could not be prepared.
I have a table that contains a few columns bound to a gridview.
In that gridview, I have an edit option to update the columns. In that situation I need to write a two update stored procedures that means I select all columns expect AudiotoName, select another columns all columns are update to raise one update query but when I select table in that have AudiotoName column that only edit to select that column it will raise second update stored procedure. I tried but it not properly working can anyone help me out.
My code:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END
Can anyone help me out?
The problem in your query is that, even if #AuditoName is true, the lower update query is running. This will re-update the table SubjectItems. You can use if...else block instead, like below:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
ELSE
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END
I have a checkboxlist. The selected (checked) items are stored in List<string> selected.
For example, value selected is monday,tuesday,thursday out of 7 days
I am converting List<> to a comma-separated string, i.e.
string a= "monday,tuesday,thursday"
Now, I am passing this value to a stored procedure as a string. I want to fire query like:
Select *
from tblx
where days = 'Monday' or days = 'Tuesday' or days = 'Thursday'`
My question is: how to separate string in the stored procedure?
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it.
Below have example:
DECLARE #str VARCHAR(500) = 'monday,tuesday,thursday'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX(',',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX(',',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + ',' , '')
END
SELECT *
FROM tblx
WHERE days IN (SELECT tDay FROM #Temp)
Try this:
CREATE FUNCTION [dbo].[ufnSplit] (#string NVARCHAR(MAX))
RETURNS #parsedString TABLE (id NVARCHAR(MAX))
AS
BEGIN
DECLARE #separator NCHAR(1)
SET #separator=','
DECLARE #position int
SET #position = 1
SET #string = #string + #separator
WHILE charindex(#separator,#string,#position) <> 0
BEGIN
INSERT into #parsedString
SELECT substring(#string, #position, charindex(#separator,#string,#position) - #position)
SET #position = charindex(#separator,#string,#position) + 1
END
RETURN
END
Then use this function,
Select *
from tblx
where days IN (SELECT id FROM [dbo].[ufnSplit]('monday,tuesday,thursday'))
try this
CREATE FUNCTION Split
(
#delimited nvarchar(max),
#delimiter nvarchar(100)
) RETURNS #t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,#delimiter,'</r><r>') + '</r></root>'
insert into #t(val)
select
r.value('.','varchar(max)') as item
from #xml.nodes('//root/r') as records(r)
RETURN
END
GO
usage:
select * from tblx where days in (select val from dbo.split('monday,tuesday,thursday',','))
I think you want this
SELECT * FROM tblx where days in ('Monday','Tuesday','Thursday')
you can get it like this:
var a = "monday,tuesday,thursday";
var sql = string.Format("Select * from tblx where days IN ('{0}')", string.Join("','",a.Split(new[] {','})));
I face the same problem, and i try all the way but not get expected solution. Finally i did like follow. Try it hope it will work...
create Function [dbo].[Split]
(
#RowData NVARCHAR(MAX),
#SplitOn NVARCHAR(5)
)
RETURNS #RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE #Cnt INT
SET #Cnt = 1
WHILE (Charindex(#SplitOn,#RowData)>0)
BEGIN
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
SET #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
SET #Cnt = #Cnt + 1
END
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(#RowData))
RETURN
END
And in the store procedure put the code like that.
select #ActualTarget= count(*) from UpdateVisitDetails where CreatedBy IN (SELECT [DATA] FROM [dbo].[Split](#AllDATS,',' ))
I have same problem. I tried this.. and this was properly run
ALTER FUNCTION [dbo].[Split]
(
#List varchar(max),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(max)
)
AS
BEGIN
IF (len(#List) <=0)
Begin
Return
End
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
Run :
SELECT * FROM dbo.Split('Apple,Banana,Mango',',')
Output:
i am inserting table in database using table datatype with the following code:
CREATE TYPE BackUpDoctorLocationAreaRoom AS TABLE (
[RoomId] bigint,
[AreaId] bigint,
[LocationId] bigint
);
Alter proc proc_tblBackUpDoctorInsert
(
#Id uniqueidentifier='',
#BackUpDoctorId uniqueidentifier='1323e1f4-7a93-4b45-9a9b-3840c32fd6d8',
#StartDate datetime='11/08/2012',
#EndDate datetime='11/09/2012',
#StartTime datetime='22:22:22',
#EndTime datetime='01:11:11',
#CreatedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#ModifiedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#createdDate datetime='11/6/12 3:09:58 AM',
#ModifiedDate datetime='11/6/12 3:09:58 AM',
#tblBackUpDoctorsForRooms BackUpDoctorLocationAreaRoom READONLY
)
as
set xact_abort on
declare #newId uniqueidentifier;
set #newId = newid();
insert into tblBackUpDoctor (Id,BackUpDoctorId,StartDate,EndDate,StartTime,EndTime,CreatedBy,ModifiedBy,
createdDate,ModifiedDate,IsActive,isdeleted) values
(#newId,
#BackUpDoctorId,
#StartDate,
#EndDate,
#StartTime,
#EndTime,
#CreatedBy,
#ModifiedBy,
#createdDate,
#ModifiedDate,
1,0)
declare #IdFortblBackUpDoctorsForRooms uniqueidentifier;
set #IdFortblBackUpDoctorsForRooms = newid();
delete from tblBackUpDoctorsForRooms where BackUpRecordId=#id and Roomid in (Select roomid from #tblBackUpDoctorsForRooms)
delete from tblbackupdoctor where id=#id
insert into tblBackUpDoctorsForRooms (BackUpRecordId,Roomid,Araeid,locationid)
Select #newId,roomid,areaid,locationid from #tblBackUpDoctorsForRooms
select #newId
This is the sp in which i am using that table.
My class file's code is :
public string InsertBackUpDoctor(ClsBackUpDoctorProp objProp, DataTable dtLocAreaRoom)
{
String ConnectionString = CCMMUtility.GetCacheForWholeApplication();
String backUpRecordId = "";
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#Id", objProp.Id);
param[1] = new SqlParameter("#BackUpDoctorId", objProp.BackUpDoctorId);
param[2] = new SqlParameter("#StartDate", objProp.StartDate);
param[3] = new SqlParameter("#EndDate", objProp.EndDate);
param[4] = new SqlParameter("#StartTime", objProp.StartTime);
param[5] = new SqlParameter("#EndTime", objProp.EndTime);
param[6] = new SqlParameter("#CreatedBy", objProp.CreatedBy);
param[7] = new SqlParameter("#ModifiedBy", objProp.ModifiedBy);
param[8] = new SqlParameter("#createdDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[9] = new SqlParameter("#ModifiedDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[10] = new SqlParameter("#CurrentDate", objProp.CurrentDate);
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString, "proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();
return backUpRecordId;
}
and here is the error which is coming when i tries to insert :
The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 12 ("#tblBackUpDoctorsForRooms"), row 0, column 0: Data type 0xF3 (user-defined table type) has a non-zero length database name specified. Database name is not allowed with a table-valued parameter, only schema name and type name are valid.
I dont know why this coming please help me..
I believe you'd have to change the way you pass your custom parameter:
Not just
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
but rather something like
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#tblBackUpDoctorsForRooms";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
parameter.Value = dtLocAreaRoom;
param[11] = parameter;
try
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
and in the call add
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString,CommandType.StoredProcedure
"proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();
How can I convert/cast this datetime format: 06/17/2012 12:00:00 AM
To this date format : 2012/06/17
in a SQL Update Statement?
I need to change to fields. BeginDate, and EndDate. Both DateTime Types.
This is my Update statement so far:
Update discount set DiscountPromotionalID = #DiscountPromotionalID,
isActive =#isActive, Title = #Title, BeginDate = #BeginDate, EndDate = #EndDate,
DiscountPercentage = #DiscountPercentage
where DiscountPromotionalID = #DiscountPromotionalID;"
If you're storing it as NVARCHAR (which you shouldn't be) you can use the following to convert it when your doing your insert/update statement. I would recommend converting this column to a proper DateTime field then you can format as you wish within the presentation layer as commentors have suggested.
Checkout this resource for all your SQL Data Formatting needs (with example sql!)
http://www.sql-server-helper.com/tips/date-formats.aspx
I believe you're looking for something like this (from the resource above):
CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD]
Like a C# DateTime value, a SQL Server DateTime value has no format: it's just a 64-bit field consisting of two 32-bit integers. The first counts days since the epoch (1 January 1900 00:00:00.000); the second counts time since start of day in 1/300ths of a second.
You apply formatting when you display it or convert it to char/varchar, either in SQL using CONVERT(), or in the client code.
Your update statement doesn't care about format: it cares about value. If you pass a C# DateTime value as a SqlParameter to your stored procedure or parameterized query, the Right Thing will happen: the CLR will magically translate the one into the other for you.
If, you pass a string as the DateTime parameter from C#, it needs to be in a format that SQL Server will recognize as a DateTime string. Assuming that's the case, the conversion from C# string to SQL Server DateTime value will likewise happen magically.
Given your update statement, code something like the following ought to do you:
public int UpdateDiscount( int discountPromotionalID , bool isActive , string title , DateTime beginDate , DateTime endDate , int discountPercentage )
{
const string updateQuery = #"
Update discount
set DiscountPromotionalID = #DiscountPromotionalID ,
isActive = #isActive ,
Title = #Title ,
BeginDate = #BeginDate ,
EndDate = #EndDate ,
DiscountPercentage = #DiscountPercentage
where DiscountPromotionalID = #DiscountPromotionalID
" ;
int rowsAffected ;
using ( SqlConnection connection = new SqlConnection( SomeConnectString ) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandText = updateQuery ;
cmd.CommandType = CommandType.Text ;
cmd.Parameters.AddWithValue( "#DiscountPromotionalID" , discountPromotionalID ) ;
cmd.Parameters.AddWithValue( "#isActive" , isActive ? 1 : 0 ) ; // C# bools are true/false; SQL bools are 1/0
cmd.Parameters.AddWithValue( "#Title" , title ) ;
cmd.Parameters.AddWithValue( "#BeginDate" , beginDate ) ;
cmd.Parameters.AddWithValue( "#EndDate" , endDate ) ;
cmd.Parameters.AddWithValue( "#DiscountPercentage" , discountPercentage ) ;
connection.Open() ;
rowsAffected = cmd.ExecuteNonQuery() ;
connection.Close() ;
}
return rowsAffected ;
}