Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Thursday, March 29, 2012

Converting Datetime from the Varchar value

I am not sure if this is the correct forum to post to for this but,

I have a stored procedure in the code like so:


dim calensql as string = "sp_scheduleworkfromcal '" & sun & "', '" & mon & "', '" & tue & "', '"
& wed & "', '" & thu & "', '" & fri & "', '" & sat & "', '" & Label1.Text & "', '" & Label2.Text & "', '"
& Label3.Text & "', '" & Label4.Text & "', '" & Label5.Text & "', '" & Label6.Text & "', '" & Label7.Text & "', " & "129"

and then in my stored procedure I have


CREATE PROCEDURE sp_scheduleworkfromcal
(@.sun VarChar(50), @.mon VarChar(50), @.tue VarChar(50), @.wed VarChar(50), @.thu VarChar(50),
@.fri VarChar(50), @.sat VarChar(50), @.dsun VarChar(50), @.dmon VarChar(50), @.dtue VarChar(50),
@.dwed VarChar(50), @.dthu VarChar(50), @.dfri VarChar(50), @.dsat VarChar(50), @.userid int)
AS
Declare @.store datetime
If @.sun != '' begin
Update servicerequests set date_scheduled=(Convert(datetime, @.dsun)) where trackingnumber=@.sun
Select @.store = rtrim(retailer) + ' ' + rtrim(storeNumber) from servicerequests where trackingnumber = @.sun
UPDATE CalendarSchedule SET cal_notes=@.store WHERE cal_date=@.dsun AND userid=@.userid
IF @.@.ROWCOUNT = 0
INSERT INTO CalendarSchedule (userid, cal_date, cal_notes) VALUES (@.userid, @.dsun, @.store)
End

and I am getting the error something like
Syntax error converting datetime from character string.

If I change the parameters in the stored procedure to datetime or varchar and get rid of the single quotes, I get incorrect sytax near "/".

I am tracking the sql statement to see where I can fix the problem, but cannot come up with a solution.

can anyone help me out with this one??
Thanks
EricI think the date format you are trying to create is wrong ... At the location ... Try investigating the line :
@.store = rtrim(retailer) + ' ' + rtrim(storeNumber)|||I don't know whether I should use datetime in the values or varchar.
In the two tables
The one the field is a datetime field and in the other table it is a Char(15)

why won't it recognize the sql statement
SQL Statement sp_scheduleworkfromcal '897', '', '', '', '903', '', '', '10/19/2003', '10/20/2003', '10/21/2003', '10/22/2003', '10/23/2003', '10/24/2003', '10/25/2003', 129

thats the trace.

E|||I have tried a variation of your code and am not receiving any errors.

Where exactly are you getting the error? Which line number, and what is the error message exactly?

What are the data types and lengths of the following columns?
-- servicerequests.date_scheduled
-- servicerequests.trackingnumber
-- CalendarSchedule.cal_date

Terri|||servicerequests.date_scheduled datetime(8)
servicerequests.trackingnumber bigint(8)
CalendarSchedule.cal_date datetime(8)

I am getting the error on the
cmd.ExecuteNonQuery() line
and the error is as follows:
System.Data.SqlClient.SqlException: Syntax error converting datetime from character string.
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
I changed the values of the textboxes from the page in the sproc from VarChar(50) to datetime as well as the data type in the CalendarSchedule table from Char(15) to datetime and still am getting the same error.

You say you tried a variation of the code? what about it did you change?
are my datatype's wrong?

Thanks
E|||I mean labels from Varchar(50) to datetime - not textboxes

Tuesday, March 27, 2012

Converting data to be inserted into a database

Hi,

I am using web matrix, and I am trying to insert a data into a MSDE database. I have used webmatrix to generate the update code, and it is executed when a button is pressed on the web page. but when the code is executed I get the error:

Syntax error converting the varchar value 'txtAmountSold.text' to a column of data type int.

So I added the following code to try to convert the data, but i am still getting the same error, with txtAmountSold.text replaced with "test"

dim test as integer
test = Convert.ToInt32(txtAmountSold.text)

Here is the whole of the function I am using:

Function AddItemToStock() As Integer

dim test as integer
test = Convert.ToInt32(txtAmountSold.text)

Dim connectionString As String = "server='(local)\Matrix'; trusted_connection=true; database='HawkinsComputers'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "INSERT INTO [stock] ([Catagory], [Type], [Name], [Manufacturer], [Price], [Weight"& _
"], [Description], [image], [OnOffer], [OfferPr"& _
"ice], [OfferDescription], [AmountInStock], [AmountOnOrder], [AmountSold]) VALUES ('CatList.SelectedItem.text', 'txtType.text', 'txtname.text', 'txtmanufacturer.text'"& _
", convert(money,'txtPrice.text'), 'txtWeight.text', 'txtDescription.text', 'txtimage.text', 'txtOnOffer"& _
".text', convert(money,'txtOfferPrice.text'), 'txtOfferDescrip"& _
"tion.text', 'txtAmountInStock.text', 'txtAmountOnOrder.text', 'test')"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try

Return rowsAffected
End Function

Any help in solving this problem would be greatly appreciated, as I am really stuck for where to go next.The probably is that you are trying to send the literal value 'test' as a parameter value.

Please use this approach instead:
Dim queryString As String = "INSERT INTO [stock] ([Catagory], [Type], [Name], [Manufacturer], [Price], [Weight"& _
"], [Description], [image], [OnOffer], [OfferPr"& _
"ice], [OfferDescription], [AmountInStock], [AmountOnOrder],[AmountSold]) VALUES (@.CatList, @.Type,@.name, @.manufacturer, @.Price, @.Weight, @.Description, @.image, @.OnOffer, @.OfferPrice, @.OfferDescription, @.AmountInStock, @.AmountOnOrder, @.test)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.Parameters.Add("@.CatList,SqlDbType.VarChar,99).Value =
CatList.SelectedItem.text
dbCommand.Parameters.Add("@.Type,SqlDbType.VarChar,50).Value =txtType.text
dbCommand.Parameters.Add("@.Name,SqlDbType.VarChar,30).Value =txtmanufacturer.text
' add all parameters in this manner
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Note that for each parameter you will need to use the appropriate SqlDbType. And if it's a character data type you will also need to specify the length.

Here are some links which should help you with using parameters:
Using Parameterized Query in ASP.NET, Part 1
Using Parameterized Query in ASP.NET, Part 2
Using Parameterized Queries in ASP.Net
How To: Protect From SQL Injection in ASP.NET|||Thanks alot for the reply, Those links will help alot aswell.

Converting Crystal Code

I'm evaluating Reporting Services and currently converting a Crystal Report
to this format. However I've ran in to a problem and it is to do with a
function written in Crystal syntax but I cannot seem to be able to convert
this logic Heres the functio
----
StringVar name = "";
If NOT IsNull({Query.FIELD1_Company}) Then
name := {Query.FIELD1_Company};
If NOT IsNull({Query.FIELD2_COMPANY}) Then
name := {Query.FIELD2_COMPANY};
If NOT IsNull({Query.FIELD3_COMPANY}) Then
name := {Query.FIELD3_COMPANY};
If NOT IsNull({Query.FIELD4_COMPANY}) Then
name := {Query.FIELD4_COMPANY};
If NOT IsNull({Query.FIELD5_COMPANY}) Then
name := {Query.FIELD5_COMPANY};
If NOT IsNull({Query.FIELD6_COMPANY}) Then
name := {Query.FIELD6_COMPANY};
If NOT IsNull({Query.FIELD7_COMPANY}) Then
name := {Query.FIELD7_COMPANY};
If NOT IsNull({Query.FIELD8_COMPANY}) Then
name := {Query.FIELD8_COMPANY};
name
----
For a start, 'Null' cannot be used, neither can System.DBNull etc only
Nothing.
StringVar is a variable declaration in Crystal. What this all does is
prevents empty fields being returned (in Column 1) and the report format is
something similar to this
Company, Number of..., Export To..., etc
SomeCompany, 1, 1, etc
NULL, 0, 3, etc
So the code prevents record number 2 from appearing in the report and
returns the company name from one of the other columns (as code above).
NOTE All columns actually return the Company name but we are simply doing a
DISTINCTCOUNT on all the other columns(Query.FIELD2_COMPANY etc), so Column 1
will always have a company name (if the code works, as in Crystal).
Any ideas on this? and thanks in advanceIs TSql It is
ISNULL(Filed1, ISNULL(Field2, ISNULL(Field3, ISNULL(Field4,
ISNULL(Field5,'')))))
What this does is if Field1 is null it moves to Field2. A lot less
complicated.
"slk55guy" wrote:
> I'm evaluating Reporting Services and currently converting a Crystal Report
> to this format. However I've ran in to a problem and it is to do with a
> function written in Crystal syntax but I cannot seem to be able to convert
> this logic Heres the function
> ----
> StringVar name = "";
> If NOT IsNull({Query.FIELD1_Company}) Then
> name := {Query.FIELD1_Company};
> If NOT IsNull({Query.FIELD2_COMPANY}) Then
> name := {Query.FIELD2_COMPANY};
> If NOT IsNull({Query.FIELD3_COMPANY}) Then
> name := {Query.FIELD3_COMPANY};
> If NOT IsNull({Query.FIELD4_COMPANY}) Then
> name := {Query.FIELD4_COMPANY};
> If NOT IsNull({Query.FIELD5_COMPANY}) Then
> name := {Query.FIELD5_COMPANY};
> If NOT IsNull({Query.FIELD6_COMPANY}) Then
> name := {Query.FIELD6_COMPANY};
> If NOT IsNull({Query.FIELD7_COMPANY}) Then
> name := {Query.FIELD7_COMPANY};
> If NOT IsNull({Query.FIELD8_COMPANY}) Then
> name := {Query.FIELD8_COMPANY};
> name;
> ----
> For a start, 'Null' cannot be used, neither can System.DBNull etc only
> Nothing.
> StringVar is a variable declaration in Crystal. What this all does is
> prevents empty fields being returned (in Column 1) and the report format is
> something similar to this
> Company, Number of..., Export To..., etc
> SomeCompany, 1, 1, etc
> NULL, 0, 3, etc
> So the code prevents record number 2 from appearing in the report and
> returns the company name from one of the other columns (as code above).
> NOTE All columns actually return the Company name but we are simply doing a
> DISTINCTCOUNT on all the other columns(Query.FIELD2_COMPANY etc), so Column 1
> will always have a company name (if the code works, as in Crystal).
> Any ideas on this? and thanks in advance
>

Sunday, March 25, 2012

Converting Access Code - FORMAT

Hello,
A colleague passed me this make-table query which works in Access, and we'd
like to automate in SQL. I did some basic debugging but now on parse, SQL
returns that Trim and Format are not recognized function nameS. I think you
can see the what formatting is doing to provide a standard string length.
Could someone advise what I need to do to get this to work in SQL? Any help
would be much appreciated. Thanks, Pancho
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) &
Trim(GVMOI2.TraceNbr) AS TraceNbrEdt, IIf(IsNumeric(GVMOI2.CreditAmtCash),
Left(Format([CreditAmtCash],"0000000000.00"),10) &
Right(Format([CreditAmtCash],"0000000000.00"),2),
"000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2!DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) &
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10) &
Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
CreditAmtChecksFmt,
IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10) &
Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
DebitAmtChecksFmt,
GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
GVMOI2.CheckReferenceNbr,
GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
GVMOI2.ThirdParty,
"0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
GVMOI2.IDNumber,
GVMOI2.IDIssueBy, GVMOI2.IDOthers
INTO MOI_Prep
FROM GVMOI2;Follow the below guidelines to convert the query.
1. & ==> +
2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
else <false> end
3. <table>!<column> ==> <table>.<column>
4. trim(<value> ) ==> rtrim(ltrim(<value> ))
-oj
"Pancho" <Pancho@.discussions.microsoft.com> wrote in message
news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
> Hello,
> A colleague passed me this make-table query which works in Access, and
> we'd
> like to automate in SQL. I did some basic debugging but now on parse, SQL
> returns that Trim and Format are not recognized function nameS. I think
> you
> can see the what formatting is doing to provide a standard string length.
> Could someone advise what I need to do to get this to work in SQL? Any
> help
> would be much appreciated. Thanks, Pancho
> SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
> GVMOI2.TaxIDType,
> GVMOI2.ApplicationCode, GVMOI2.AccountNo,
> Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) &
> Trim(GVMOI2.TraceNbr) AS TraceNbrEdt, IIf(IsNumeric(GVMOI2.CreditAmtCash),
> Left(Format([CreditAmtCash],"0000000000.00"),10) &
> Right(Format([CreditAmtCash],"0000000000.00"),2),
> "000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2!DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) &
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10)
> &
> Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
> CreditAmtChecksFmt,
> IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10)
> &
> Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
> DebitAmtChecksFmt,
> GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
> GVMOI2.CheckReferenceNbr,
> GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
> GVMOI2.ThirdParty,
> "0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
> GVMOI2.IDNumber,
> GVMOI2.IDIssueBy, GVMOI2.IDOthers
> INTO MOI_Prep
> FROM GVMOI2;
>
>|||OJ,
Thank you for these clear instructions. I will try these tomorrow. Looks
good!
Best Wishes,
P
"oj" wrote:

> Follow the below guidelines to convert the query.
> 1. & ==> +
> 2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
> else <false> end
> 3. <table>!<column> ==> <table>.<column>
> 4. trim(<value> ) ==> rtrim(ltrim(<value> ))
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
>
>|||Hi oj,
I replaced & with +, ! with . on table.column names, and
rtrim(ltrim(<value> ) parses OK now.
Pls take a look at the revised script. I don't quite follow how to change
the iif to case when. I am getting an incorrect syntax error near THEN.
Please let me know what I'm doing wrong on the first CASE line and I'll fix
the rest the same way. Thanks! P
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
CASE WHEN (IsNumeric(GVMOI2.CreditAmtCash)) THEN
Left(Format([CreditAmtCash],"0000000000.00"),10) +
Right(Format([CreditAmtCash],"0000000000.00"),2), ELSE FALSE
"000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2.DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) +
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10) +
Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
CreditAmtChecksFmt,
IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10) +
Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
DebitAmtChecksFmt,
GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
GVMOI2.CheckReferenceNbr,
GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
GVMOI2.ThirdParty,
"0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
GVMOI2.IDNumber,
GVMOI2.IDIssueBy, GVMOI2.IDOthers
INTO MOI_Prep
FROM GVMOI2;
"oj" wrote:

> Follow the below guidelines to convert the query.
> 1. & ==> +
> 2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
> else <false> end
> 3. <table>!<column> ==> <table>.<column>
> 4. trim(<value> ) ==> rtrim(ltrim(<value> ))
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
>
>|||There is no format() in sqlserver. You'd want to use convert() instead.
IIf(IsNumeric(GVMOI2.DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) +
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
==>
case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
else replicate('0',10) AS DebitAmtCashFmt,
-oj
"Pancho" <Pancho@.discussions.microsoft.com> wrote in message
news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
> Hi oj,
> I replaced & with +, ! with . on table.column names, and
> rtrim(ltrim(<value> ) parses OK now.
> Pls take a look at the revised script. I don't quite follow how to change
> the iif to case when. I am getting an incorrect syntax error near THEN.
> Please let me know what I'm doing wrong on the first CASE line and I'll
> fix
> the rest the same way. Thanks! P
> SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
> GVMOI2.TaxIDType,
> GVMOI2.ApplicationCode, GVMOI2.AccountNo,
> Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
> RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
> CASE WHEN (IsNumeric(GVMOI2.CreditAmtCash)) THEN
> Left(Format([CreditAmtCash],"0000000000.00"),10) +
> Right(Format([CreditAmtCash],"0000000000.00"),2), ELSE FALSE
> "000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10)
> +
> Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
> CreditAmtChecksFmt,
> IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10)
> +
> Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
> DebitAmtChecksFmt,
> GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
> GVMOI2.CheckReferenceNbr,
> GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
> GVMOI2.ThirdParty,
> "0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
> GVMOI2.IDNumber,
> GVMOI2.IDIssueBy, GVMOI2.IDOthers
> INTO MOI_Prep
> FROM GVMOI2;
>
> "oj" wrote:
>|||Thanks again oj. I have marked both of your posts as helpful and will try
this code.
Best Regards,
p
"oj" wrote:

> There is no format() in sqlserver. You'd want to use convert() instead.
> IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> ==>
> case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
> right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
> else replicate('0',10) AS DebitAmtCashFmt,
>
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
>
>|||oj,
This is getting closer but now I get an incorrect syntax near the word AS on
the last line of the section below:
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
CASE WHEN IsNumeric(GVMOI2.CreditAmtCash)=1 THEN
Right(Convert(varchar,convert(money,1000
000000000+GVMOI2.CreditAmtCash)),13)
ELSE
Replicate('0',13) AS CashCRFmt,
It looks like they want to name the column CreditAmtCash when there is a
numeric value and name it CashCRFmt when the value is non-numeric. Let me
know if I am using Replicate correctly.
Thanks,
p
"oj" wrote:

> There is no format() in sqlserver. You'd want to use convert() instead.
> IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> ==>
> case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
> right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
> else replicate('0',10) AS DebitAmtCashFmt,
>
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
>
>

Tuesday, March 20, 2012

convert year from mm/dd/yyyy to mm/dd/yy

I am working with a chart. I want to display the year on the X axis as mm/dd/yy. I have tried entering yy, etc into the format code field and have had no luck.

Any comments are appreciated.

Reporting Services uses similar formatting commands to Excel. You should be able to use MM/dd/yy.

If that doesn't work, another way would be to create a function that would return the values in a string format and parse the string. Something like:

public function getDate(dt as string) as string

string dt = left(dt,6) & right(dt,2)

return dt

end function

cheers,

Andrew

|||

Thanks! I was able to get this to work

CONVERT(varchar(12), field_name, 10) AS Date

Monday, March 19, 2012

Convert Varchar is inconsistent

Hi All,
I have a source table which contains a customer code in a CHAR(8) column.
The customer codes are only ever 5 or 6 characters long, so in the reporting
tables I am extracting data out to, I have been specifying the customer code
column as a VARCHAR(8). [I am aware that for such a small variance its
debatable whether its worth the overhead of having a VARCHAR column, but jus
t
run with me on this one].
In each of the stored procs I have explicitly stated CONVERT(VARCHAR(8),
CustomerCode) but some of my tables still contain a padded 8 character
customer code, despite the datatype being VARCHAR(8) and the sp explicitly
stating convert this code to a varchar. I can verify this with the LEN and
DATALENGTH commands. All the tables are in the same database and I havent
been playing with the SET ANSI_PADDING setting either.
I'm thinking that SQL is evaluating whether its worth doing the conversion,
and sometimes it thinks its worthwhile, and other times it doesnt (maybe on
whether it comes accross a 5 or a 6 character customer first?). However, I
cant find anything about this 'machine learning' feature in BOL.
Has anyone come accross this before? and if so, what did you do to force SQL
into storing the data in the column as a VARCHAR?
TIA,
Bill PColumns of type CHAR are padded with space (See ANSI_PADDING in BOL), so whe
n
you convert to varchar you are converting also the spaces and they are not
trimmed in the convertion. You need to rtrim the converted value.
Example:
create table t (
colA char(8) not null
)
insert into t values('a')
insert into t values('bb')
insert into t values('ccc')
insert into t values('dddd')
insert into t values('eeeee')
insert into t values('gggggg')
insert into t values('hhhhhhhh')
select
convert(varchar(8), colA),
datalength(convert(varchar(8), colA)),
rtrim(convert(varchar(8), colA)),
datalength(rtrim(convert(varchar(8), colA)))
from
t
select
convert(varchar(1), space(1)),
datalength(convert(varchar(1), space(1))),
len(convert(varchar(1), space(1)))
drop table t
go
AMB
"Bill P" wrote:

> Hi All,
> I have a source table which contains a customer code in a CHAR(8) column.
> The customer codes are only ever 5 or 6 characters long, so in the reporti
ng
> tables I am extracting data out to, I have been specifying the customer co
de
> column as a VARCHAR(8). [I am aware that for such a small variance its
> debatable whether its worth the overhead of having a VARCHAR column, but j
ust
> run with me on this one].
> In each of the stored procs I have explicitly stated CONVERT(VARCHAR(8),
> CustomerCode) but some of my tables still contain a padded 8 character
> customer code, despite the datatype being VARCHAR(8) and the sp explicitly
> stating convert this code to a varchar. I can verify this with the LEN an
d
> DATALENGTH commands. All the tables are in the same database and I havent
> been playing with the SET ANSI_PADDING setting either.
> I'm thinking that SQL is evaluating whether its worth doing the conversion
,
> and sometimes it thinks its worthwhile, and other times it doesnt (maybe o
n
> whether it comes accross a 5 or a 6 character customer first?). However,
I
> cant find anything about this 'machine learning' feature in BOL.
> Has anyone come accross this before? and if so, what did you do to force S
QL
> into storing the data in the column as a VARCHAR?
> TIA,
> Bill P|||On Tue, 8 Mar 2005 06:19:05 -0800, Bill P wrote:
(snip)
> [I am aware that for such a small variance its
>debatable whether its worth the overhead of having a VARCHAR column, but ju
st
>run with me on this one].
Hi Bill,
It's not even debatable. CHAR(6) (not CHAR(8)!!) will always take 6
bytes, VARCHAR(6) (or more than 6) will take 7 or 8 bytes for 5 or 6
characters.
But okay - I'll run with you.

>In each of the stored procs I have explicitly stated CONVERT(VARCHAR(8),
>CustomerCode) but some of my tables still contain a padded 8 character
>customer code, despite the datatype being VARCHAR(8) and the sp explicitly
>stating convert this code to a varchar.
That's correct. As CHAR(8), the data got padded with spaces. The
conversion to VARCHAR won't remove the trailing spaces.
Use CONVERT(varchar(8), RTRIM(CustomerCode)) to remove the trailing
spaces and really reduce the length.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi Alejandro,
Many thanks for that. Thats something that I hadnt considered, but it makes
total sense. I will ensure that I perform RTRIMs in all the SPs to ensure
consistency.
I doesnt answer why some of my tables were RTRIMing themselves and some
werent though? Thats not something I want you to answer as I am more than
happy with the solution, but its still something that I dont at this point
fully understand. If I find out, I will post it to the group.
Thanks once again,
Bill P
"Alejandro Mesa" wrote:
> Columns of type CHAR are padded with space (See ANSI_PADDING in BOL), so w
hen
> you convert to varchar you are converting also the spaces and they are not
> trimmed in the convertion. You need to rtrim the converted value.
> Example:
> create table t (
> colA char(8) not null
> )
> insert into t values('a')
> insert into t values('bb')
> insert into t values('ccc')
> insert into t values('dddd')
> insert into t values('eeeee')
> insert into t values('gggggg')
> insert into t values('hhhhhhhh')
> select
> convert(varchar(8), colA),
> datalength(convert(varchar(8), colA)),
> rtrim(convert(varchar(8), colA)),
> datalength(rtrim(convert(varchar(8), colA)))
> from
> t
> select
> convert(varchar(1), space(1)),
> datalength(convert(varchar(1), space(1))),
> len(convert(varchar(1), space(1)))
> drop table t
> go
>
> AMB
>
> "Bill P" wrote:
>|||Hi Hugo,
If only life were that simple. If I set these up as CHAR(6) or VARCHAR(6)
you can bet your bottom dollar that the some bright spark will create a new
customer with an 8 character code, simply because the ERP system lets them.
But I take your point.
Bill :-)
"Hugo Kornelis" wrote:

> On Tue, 8 Mar 2005 06:19:05 -0800, Bill P wrote:
> (snip)
> Hi Bill,
> It's not even debatable. CHAR(6) (not CHAR(8)!!) will always take 6
> bytes, VARCHAR(6) (or more than 6) will take 7 or 8 bytes for 5 or 6
> characters.
> But okay - I'll run with you.
>
> That's correct. As CHAR(8), the data got padded with spaces. The
> conversion to VARCHAR won't remove the trailing spaces.
> Use CONVERT(varchar(8), RTRIM(CustomerCode)) to remove the trailing
> spaces and really reduce the length.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>|||On Tue, 8 Mar 2005 07:07:04 -0800, Bill P wrote:
(snip)
> the ERP system lets them.
Ah, I see how that changes things. :-)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

convert update from access to sql and have an error.

I am trying to convert code I have working for access to work with SQL.
fldName, fldEmail, ID are the names in the database. recNum does have the value of the record that I want to edit. Here is the error I am getting.
System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '?'.

And here is the stack trace (which I don't know how to read except for the line the error is on)
 [SqlException: Line 1: Incorrect syntax near '?'.]
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) +723
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +194
goodellweb.adm_contact.editNow_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\webroot\goodellweb\adm\adm_contacts.aspx.vb:306
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain() +1315

here is my code.

Dim editSQL As String = "Update tbEmail Set fldName=?, fldEmail=? Where ID=?"
Dim SqlConn As New SqlConnection(ConnStr)
Dim Cmd As New SqlCommand(editSQL, SqlConn)
Cmd.Parameters.Add(New SqlParameter("@.fldName", nameEdit.Text))
Cmd.Parameters.Add(New SqlParameter("@.fldEmail", emailEdit.Text))
Cmd.Parameters.Add(New SqlParameter("@.recNum", recNum))

SqlConn.Open()
Try
Cmd.ExecuteNonQuery()
Finally
SqlConn.Close()
End Try
Response.Write("recNum " & recNum & " <br>")

Thanks
MichaelSQL uses named parameters. Try:

Dim editSQL As String = "Update tbEmail Set fldName=@.fldName, fldEmail=@.fldEmail Where ID=@.recNum"

Dim SqlConn As New SqlConnection(ConnStr)

Dim Cmd As New SqlCommand(editSQL, SqlConn)

Cmd.Parameters.Add(New SqlParameter("@.fldName", nameEdit.Text))

Cmd.Parameters.Add(New SqlParameter("@.fldEmail", emailEdit.Text))

Cmd.Parameters.Add(New SqlParameter("@.recNum", recNum))

|||hanks douglas
That did take care of the error, but it is not updating. Maybe it is updating its just updating what was already in the database and now the new data. Is there a way to see if the new data in the textbox is present? When I do a
 Response.Write("email " & emailEdit.Text & " <br>")
at the end of the code it shows the data in the database. Should it be the new data?
Thanks
Michael|||Just tried this and it updated.

Cmd.Parameters.Add(New SqlParameter("@.fldName", "test"))

So my new data is not getting to the right place.
So what am i missing?
Thanks
Michael|||You need to have your data binding only take place when IsPostback is false:

If IsPostback=false then
' data bind ONLY here
End If

What you do otherwise is re-read the data from the database and "update" with the data from the database.

Convert to Unicode

Hi all
I have an Sql2k database with SQL Server Sort Order 185 on Code Page 1252
for non-Unicode Data
Now customers from latvia needs to use this database concurrently , is it
possible to convert the tables to Unicode when it is already running live?
Best regards
Henrik Hasselblad
SYSteamThis is a multi-part message in MIME format
--=_NextPart_000_61137148
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
You will have to change all varchars to nvarchars. You will need to
check that no string is bigger than 4000 chars and that you don't
violate the 8060 byte max rowsize.
Changing the values via alter column may cause problems too.
You can chnage the collation via alter database.
Nigel Rivett
www.nigelrivett.net
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
--=_NextPart_000_61137148
Content-Type: text/html; name="_alt.0"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment; filename="_alt.0"
=EF=BB=BF<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4=2E0= Transitional//EN">
&

Careful=2E Is transdate your= partitioning
column or is month? Make sure to include the partitioning= column in the
WHERE clause=2E
-- Tom
----=--Thomas
A=2E Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist,= SQL Server
ProfessionalToronto, ON Canadahref=3D"www=2Epinnaclepublishi=">http://www=2Epinnaclepublishing=2Ecom/sql">www=2Epinnaclepublishi=ng=2Ecom/sql
"George" wrote in
message ne=ws:E5C82E40-6AE6-444D-B939-FC55D20B19C4@.microsoft=2Ecom=2E=2E=2EThanks
a lot for Tom and Dan=2E I have changed the partition tables= divided by month, and
created the table with CHECK constraint=2E My script only= references V_use once
per query, and, even as simple as 'select * from v_use where= transdate between
@.d1 and @.d2' will call every base table, although most of them= only takes 1%~2%
total cost=2E Thanks again=2E
--=_NextPart_000_61137148--

Convert to SQL Function! Help!

Can u help me transform this code into sql function?

/* Append modulus 11 check digit to supplied string of digits. */
function GenMOD11( $base_val )
{
$result = "";
$weight = array( 2, 3, 4, 5, 6, 7,
2, 3, 4, 5, 6, 7,
2, 3, 4, 5, 6, 7,
2, 3, 4, 5, 6, 7 );

/* For convenience, reverse the string and work left to right. */
$reversed_base_val = strrev( $base_val );
for ( $i = 0, $sum = 0; $i < strlen( $reversed_base_val ); $i++ )
{
/* Calculate product and accumulate. */
$sum += substr( $reversed_base_val, $i, 1 ) * $weight[ $i ];
}

/* Determine check digit, and concatenate to base value. */
$remainder = $sum % 11;
switch ( $remainder )
{
case 0:
$result = $base_val . 0;
break;
case 1:
$result = "n/a";
break;
default:
$check_digit = 11 - $remainder;
$result = $base_val . $check_digit;
break;
}Owh..i forget.. I'm using SQL Server 2000|||moving thread to SQL Server forum|||Can you explain to us what the above function actually does (step by step preferred) and then we can see if we can help! :)|||The reversing confuses me slightly. Is the last digit always multiplied by 2?|||May I contribute:-- ptp 20070806 SQL Server mod-11 function
-- See http://www.dbforums.com/showthread.php?t=1621130 for discussion
-- Note: Mod-11 was once a well known checkdigit algorithm. It was implemented in hardware
-- on the 129 keypunch, and it still used in ISBN and banking applications in 2007

CREATE FUNCTION dbo.fMod11(@.pcFundus VARCHAR(20))
RETURNS VARCHAR(21) AS

BEGIN
DECLARE @.iAccumulator BIGINT -- Accumulator for weighted sum
, @.iDigits INT -- Digit place value
, @.iNoise INT -- Noise characters ignored
, @.cChar CHAR(1) -- Current working character
, @.cResult VARCHAR(21) -- Result value to return
, @.cWork VARCHAR(21) -- Scratch buffer

SET @.cResult = @.pcFundus -- Assume we return what we got
SET @.cWork = Reverse(@.pcFundus) -- Reverse to make string handling simpler
SET @.iAccumulator = 0 -- Accumulator starts at zero
SET @.iDigits = 1 -- 1 is offest for the check digit

WHILE 0 < Len(@.cWork) -- Loop to process all characters
BEGIN
SET @.cChar = Left(@.cWork, 1) -- Current char is leftmost
SET @.cWork = SubString(@.cWork, 2, 21) -- then peel it off the buffer

IF 0 < CharIndex(@.cChar, '0123456789') -- Digit character
BEGIN
SET @.iDigits = 1 + @.iDigits -- bump digit count
SET @.iAccumulator = @.iDigits * (Ascii(@.cChar) - 48) + @.iAccumulator
END
ELSE IF 0 < CharIndex(@.cChar, ' -') -- Defined "noise" character?
SET @.iNoise = 1 + @.iNoise
ELSE -- Garbage, bail out!
BEGIN
SET @.cResult = NULL
SET @.cWork = ''
END
END

RETURN @.cResult + SubString('0123456789XX', 12 - @.iAccumulator % 11, 1)
END
GO
SELECT d1 + d0, dbo.fMod11(d1 + d0) -- Prove that we've got it correct
FROM (
SELECT 0 AS d0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4
UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS z0
CROSS JOIN (
SELECT 0 AS d1 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40
UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS z1
ORDER BY d1 + d0
GO
DROP FUNCTION dbo.fMod11 -- Tidy up after we've played in the sandbox-PatP|||Pat, I don't believe that your @.iDigits does the same thing as massspectrometry's weight array as the string gets longer than 6 characters.
You seem to multiply the 7th number by 8, and mass's function multiplies it by 2.|||I'll conceed that my Transact-SQL function and the PHP function aren't identical.

My algorithm implements Mod-11 as it is used for ISBN, banking, etc. It specifically allows for "noise characters" that are permissible in those uses, and it correctly computes the checksum for a fundus value with a value of zero or a remainder of ten (using an X for the checksum character).

-PatP|||Can you explain to us what the above function actually does (step by step preferred) and then we can see if we can help! :)

Hai..thank you for offering.. I'm trying to make a sql function that will perform similarly like this url http://www.eclectica.ca/howto/modulus-11-self-check.php

I have 7 digits data (SERIALNO), and i want to get the modulus 11 from this 7 digits data..

For example..
SERIALNO || MODULO 11
1000001 || 10000017
1000002 || 10000025
1000003 || 10000033
1000004 || 10000041

Can it be done? How?|||Here is the code with the 5250 bug faithfully re-implemented:-- ptp 20070806 SQL Server implemented of IBM 5250 mod-11 function
-- See http://www.dbforums.com/showthread.php?t=1621130 for discussion
-- Note: Mod-11 was once a well known checkdigit algorithm. A derivative of mod-11
-- was implemented in hardware on the 5250 terminal

CREATE FUNCTION dbo.fMod11(@.pcFundus VARCHAR(20))
RETURNS VARCHAR(21) AS

BEGIN
DECLARE @.iAccumulator BIGINT -- Accumulator for weighted sum
, @.iDigits INT -- Digit place value
, @.iNoise INT -- Noise characters ignored
, @.cChar CHAR(1) -- Current working character
, @.cResult VARCHAR(21) -- Result value to return
, @.cWork VARCHAR(21) -- Scratch buffer

SET @.cResult = @.pcFundus -- Assume we return what we got
SET @.cWork = Reverse(@.pcFundus) -- Reverse to make string handling simpler
SET @.iAccumulator = 0 -- Accumulator starts at zero
SET @.iDigits = 1 -- 1 is offest for the check digit

WHILE 0 < Len(@.cWork) -- Loop to process all characters
BEGIN
SET @.cChar = Left(@.cWork, 1) -- Current char is leftmost
SET @.cWork = SubString(@.cWork, 2, 21) -- then peel it off the buffer

IF 0 < CharIndex(@.cChar, '0123456789') -- Digit character
BEGIN
SET @.iDigits = -- Next 5250 digit weight
CASE
WHEN 7 = @.iDigits THEN 2
ELSE 1 + @.iDigits
END
SET @.iAccumulator = @.iDigits * (Ascii(@.cChar) - 48) + @.iAccumulator
END
ELSE IF 0 < CharIndex(@.cChar, ' -') -- Defined "noise" character?
SET @.iNoise = 1 + @.iNoise
ELSE -- Garbage, bail out!
BEGIN
SET @.cResult = NULL
SET @.cWork = ''
END
END

RETURN @.cResult + SubString('0123456789XX', 12 - @.iAccumulator % 11, 1)
END
GO
SELECT dbo.fMod11('100000' + d)
FROM (SELECT '0' AS d UNION SELECT '1' UNION SELECT '2' UNION SELECT '3' UNION SELECT '4' UNION SELECT '5') AS z

SELECT d1 + d0, dbo.fMod11(d1 + d0) -- Prove that we've got it correct
FROM (
SELECT 0 AS d0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4
UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS z0
CROSS JOIN (
SELECT 0 AS d1 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40
UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS z1
ORDER BY d1 + d0
GO
DROP FUNCTION dbo.fMod11 -- Tidy up after we've played in the sandbox-PatP|||Erm.. i feel really shy of asking this.. how to call the function? (embarrassed)|||See the sample code at the end of the snippet that I posted. Your test is in there.

-PatP|||Thank you pat phelan.. in the code here :

SELECT dbo.fMod11('100000' + d)
FROM (SELECT '0' AS d UNION SELECT '1' UNION SELECT '2' UNION SELECT '3' UNION SELECT '4' UNION SELECT '5') AS z

For example if i have 100,000 data.. starting from 1000001 until 1100000.. How am i to code it? Is it one by one?|||FYI - http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=87357|||None of the code or links worked for my situation. I'm posting what I hope is a generic mod 11 user defined function. I'm sure there are improvements that could be made to it, but it works for my need (10 numeric digits, last digit being a mod11 check digit).

/*
Checks if a number passes the Mod11 checksum algorithm.

Input:
@.NumberToCheck = the number to check for validity (last digit is the check digit)

Returns:
1 = the number provided passes the Mod11 checksum algorithm
0 = the number provided does not pass the Mod11 checksum algorithm
*/

CREATE Function dbo.ufn_Mod11(@.NumberToCheck as varchar(10))
Returns bit As
Begin
/*
-- FOR TESTING --------
Declare @.NumberToCheck as varchar(10)
Set @.NumberToCheck = '7830834260'
Set @.NumberToCheck = '7806812519'
-- FOR TESTING --------
*/
Declare @.CheckDigit int
Declare @.Counter int
Declare @.IsValid bit
Declare @.Product int
Declare @.Sum int

-- Assume it is not valid.
Set @.IsValid = 0

-- Number must not be null, must be numeric, must be ten digits.
If @.NumberToCheck Is Not Null And IsNumeric(@.NumberToCheck) = 1 And Len(@.NumberToCheck) = 10
Begin
Set @.Counter = 1
Set @.Sum = 0

-- Reverse the number being checked.
Set @.NumberToCheck = Reverse(@.NumberToCheck)

-- Iterate through all digits except the last digit.
While @.Counter <= Len(@.NumberToCheck)
Begin
-- Multiply the digit by its position, starting with the second one.
If @.Counter > 1
Begin
Set @.Product = SubString(@.NumberToCheck, @.Counter, 1)

Set @.Product = @.Product * @.Counter

-- Sum the current product.
Set @.Sum = @.Sum + @.Product
End

Set @.Counter = @.Counter + 1
End

Set @.CheckDigit = @.Sum % 11

-- If the check digit is ten, just set it to zero.
If @.CheckDigit = 10
Begin
Set @.CheckDigit = 0
End

-- Compare the calculated check digit to the original last digit,
-- which is now the first since it was reversed.
If @.CheckDigit = Left(@.NumberToCheck, 1)
Begin
Set @.IsValid = 1
End
End

Return @.IsValid
End

convert to set-based

I need help understanding this code and seeing if it can be converted to
set-based.
Declare @.Id int
Declare @.companyId numeric(18,0)
Declare @.franchiseId numeric(18,0)
--I understand this part where a table is created and populated
Declare @.tblCompanyFranchise Table( [Id] int, companyId numeric(18,0),
franchiseId numeric(18,0))
Declare @.pinId Varchar(30)
insert into @.tblCompanyFranchise([Id],companyId , franchiseId )
select [ID],numCompanyId,numFranchiseId from dbo.tblCompanyFranchise
where pinId is null
While(SELECT COUNT(*) FROM @.tblCompanyFranchise) > 0
Begin
--I don't understand where [id], companyid and franchiseid come from here to
compare to what is in the temp @.tblcompanyfranchise table
SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
@.tblCompanyFranchise
--here deleting row just selected above
DELETE FROM @.tblCompanyFranchise WHERE companyId=@.companyId
and franchiseId=@.franchiseId and [id] =@.id
--not sure purpose of attempts here
Declare @.attempts int
Set @.attempts = 10
while(@.attempts > 0)
Begin
--set @.pinid as unique
--not sure why add @.id to part of pinid
Set @.pinId = Abs(CheckSum(NEWID()))
Set @.pinId = cast ( (cast (substring(@.pinId,1,10-len(@.Id)) as varchar) +
cast (@.Id as varchar)) as Varchar)
--this part below I don't understand. Is the update statement at the bottom
outside of the if statement below? What is the purpose of the attempts? IF
the count is not > 0 then attempts are set to 0. Correct?
if((Select count(*) from dbo.tblCompanyFranchise where pinid = @.pinId) > 0)
Begin
Set @.attempts = @.attempts - 1
If @.attempts = 0
Set @.pinId = null
End
Else
Begin
Set @.attempts = 0
End
End
Update dbo.tblCompanyFranchise set pinId = @.pinId
where numCompanyId=@.companyId and numFranchiseId=@.franchiseId and [id] =@.id
End
Go
Is there a set-based way to do the same thing?Looks to me like it's trying to create a pin for each companyid, but it's
worried that the pin might not be unique. To combat that, they put the
companyid at the end of it, padding to 10 characters. I suppose then though,
they might have the situation where there are two pins the same, if the
companyids are, say, 102 and 3102.
I would suggest that the logic be investigated, and replaced with something
that is going to produce a unique string each time, so that it doesn't need
to do each one individually. For example, if you are allowed a pin of 30
characters (as per the declare statement), then why not use all 10
characters of the random number (pad it out if necessary) and then put the
id on the end. That way, there will never be an overlap, as the digits from
position 11 on would be unique (just longer for larger numbers).
If the pin has to be 10 characters, then perhaps you could put a hyphen in
before the companyid section?
If all the characters have to be digits, then perhaps pad the companyid out
to a known number of digits - but that will restrict the number of companies
you could have in the system.
Of course, the chance of an overlap is really quite small, so you could put
a unique index on the pinid field, and just retry the query if you get an
error.
update dbo.tblCompanyFranchise
set pinId = cast ( (cast (substring(cast(abs(CheckSum(NEWID())) as
varchar),1,10-len(Id)) as varchar) + cast (Id as varchar)) as Varchar)
where pinId is null
Rob
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:B80E4114-572B-4B03-9095-99BC70A780E3@.microsoft.com...
>I need help understanding this code and seeing if it can be converted to
> set-based.
> Declare @.Id int
> Declare @.companyId numeric(18,0)
> Declare @.franchiseId numeric(18,0)
> --I understand this part where a table is created and populated
> Declare @.tblCompanyFranchise Table( [Id] int, companyId numeric(18,0),
> franchiseId numeric(18,0))
> Declare @.pinId Varchar(30)
> insert into @.tblCompanyFranchise([Id],companyId , franchiseId )
> select [ID],numCompanyId,numFranchiseId from dbo.tblCompanyFranchise
> where pinId is null
> While(SELECT COUNT(*) FROM @.tblCompanyFranchise) > 0
> Begin
> --I don't understand where [id], companyid and franchiseid come from here
> to
> compare to what is in the temp @.tblcompanyfranchise table
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
> --here deleting row just selected above
> DELETE FROM @.tblCompanyFranchise WHERE companyId=@.companyId
> and franchiseId=@.franchiseId and [id] =@.id
> --not sure purpose of attempts here
> Declare @.attempts int
> Set @.attempts = 10
> while(@.attempts > 0)
> Begin
> --set @.pinid as unique
> --not sure why add @.id to part of pinid
> Set @.pinId = Abs(CheckSum(NEWID()))
> Set @.pinId = cast ( (cast (substring(@.pinId,1,10-len(@.Id)) as varchar) +
> cast (@.Id as varchar)) as Varchar)
> --this part below I don't understand. Is the update statement at the
> bottom
> outside of the if statement below? What is the purpose of the attempts? IF
> the count is not > 0 then attempts are set to 0. Correct?
> if((Select count(*) from dbo.tblCompanyFranchise where pinid = @.pinId) >
> 0)
> Begin
> Set @.attempts = @.attempts - 1
> If @.attempts = 0
> Set @.pinId = null
> End
> Else
> Begin
> Set @.attempts = 0
> End
> End
> Update dbo.tblCompanyFranchise set pinId = @.pinId
> where numCompanyId=@.companyId and numFranchiseId=@.franchiseId and [id]
> =@.id
> End
> Go
> Is there a set-based way to do the same thing?
> --
>|||I thought newid() always produced a unique value? Do you know what the
purpose of the 10 "attempts" toward the bottom was?
Thanks,
--
Dan D.
"Rob Farley" wrote:

> Looks to me like it's trying to create a pin for each companyid, but it's
> worried that the pin might not be unique. To combat that, they put the
> companyid at the end of it, padding to 10 characters. I suppose then thoug
h,
> they might have the situation where there are two pins the same, if the
> companyids are, say, 102 and 3102.
> I would suggest that the logic be investigated, and replaced with somethin
g
> that is going to produce a unique string each time, so that it doesn't nee
d
> to do each one individually. For example, if you are allowed a pin of 30
> characters (as per the declare statement), then why not use all 10
> characters of the random number (pad it out if necessary) and then put the
> id on the end. That way, there will never be an overlap, as the digits fro
m
> position 11 on would be unique (just longer for larger numbers).
> If the pin has to be 10 characters, then perhaps you could put a hyphen in
> before the companyid section?
> If all the characters have to be digits, then perhaps pad the companyid ou
t
> to a known number of digits - but that will restrict the number of compani
es
> you could have in the system.
> Of course, the chance of an overlap is really quite small, so you could pu
t
> a unique index on the pinid field, and just retry the query if you get an
> error.
> update dbo.tblCompanyFranchise
> set pinId = cast ( (cast (substring(cast(abs(CheckSum(NEWID())) as
> varchar),1,10-len(Id)) as varchar) + cast (Id as varchar)) as Varchar)
> where pinId is null
> Rob
> "Dan D." <DanD@.discussions.microsoft.com> wrote in message
> news:B80E4114-572B-4B03-9095-99BC70A780E3@.microsoft.com...
>
>|||>> s there a set-based way to do the same thing? <<
What is this nightmare of poorly formatted insanely proprietary code
supposed to do? Without a spec, it is pretty hard to answer your
querstion. I have the feeling that this crap is not using a relatioanl
key at all, but that it is randomly trying to construct an unverifiable
exposed locator on the fly.|||Dan,

>I thought newid() always produced a unique value?
It does. But your code isn't using it in its standard form. It's grabbing
its checksum, and its absolute value, so that just makes it a random number
less than 2^31.
But then you change the last characters of that number with the id from the
table. Eg... if you have an id of 100342, your 10-digit random number might
be:
2834100342
But the whole reason for doing it one by one is that your code is worried
that it might not be unique. But it's going to be _probably_ unique - the
only chance of overlaps is where you have two numbers that overlap already.
For example, there's a 1/1000 chance that the same number above could be
generated for company 4100342. And it figures that it should be able to find
a unique number some time in the first 10 tries - which it shouldn't have
any problem doing at all.
The chance of each one being unique is very high. Not high enough to warrant
doing each one individually and checking each time. But if you need it to be
enforced, then do it with a unique key, and just put a check in to see that
the update hasn't broken the rule. If it has, just re-run it.
Let's have a quick think about where the possible overlaps are:
Record 100342 could overlap with:
record 2 (1/1000000000 chance)
record 42 (1/100000000 chance)
record 342 (1/10000000 chance)
record 1100342 (1/1000 chance)
record 2100342 (1/1000 chance)
...etc
If there's a really good business reason for the uniqueness, this is enough
of a risk to make it worth enforcing, but you could update hundreds of
thousands of records at a time without noticing any overlaps.
Rob
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:F8787F1F-4AC0-405C-9E8E-5ACF7841F11D@.microsoft.com...
>I thought newid() always produced a unique value? Do you know what the
> purpose of the 10 "attempts" toward the bottom was?
> Thanks,
> --
> Dan D.
>
> "Rob Farley" wrote:
>|||The pinid column is a varchar(30) so if the contractor was really worried
about uniqueness, I don't know why he didn't use more of the id field. The i
d
itself is also supposed to be unique so the chance of combining the checksum
of newid() and all of the id field is pretty small.
I ran your query and it took 6 seconds. The original code took 4 hours.
Can you tell me what how this part of the code works:
SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
@.tblCompanyFranchise
I interpret it to mean select the first record from @.tblCompanyFranchise
where the @.id in @.tblCompanyFranchise equals [id] and where @.companyid equals
companyid and where @.franchiseid equals franchiseid. But where does the valu
e
for [id], companyid and franchiseid come from?
Thanks so much for your help Rob.
Dan D.
"Rob Farley" wrote:

> Dan,
>
> It does. But your code isn't using it in its standard form. It's grabbing
> its checksum, and its absolute value, so that just makes it a random numbe
r
> less than 2^31.
> But then you change the last characters of that number with the id from th
e
> table. Eg... if you have an id of 100342, your 10-digit random number migh
t
> be:
> 2834100342
> But the whole reason for doing it one by one is that your code is worried
> that it might not be unique. But it's going to be _probably_ unique - the
> only chance of overlaps is where you have two numbers that overlap already
.
> For example, there's a 1/1000 chance that the same number above could be
> generated for company 4100342. And it figures that it should be able to fi
nd
> a unique number some time in the first 10 tries - which it shouldn't have
> any problem doing at all.
> The chance of each one being unique is very high. Not high enough to warra
nt
> doing each one individually and checking each time. But if you need it to
be
> enforced, then do it with a unique key, and just put a check in to see tha
t
> the update hasn't broken the rule. If it has, just re-run it.
> Let's have a quick think about where the possible overlaps are:
> Record 100342 could overlap with:
> record 2 (1/1000000000 chance)
> record 42 (1/100000000 chance)
> record 342 (1/10000000 chance)
> record 1100342 (1/1000 chance)
> record 2100342 (1/1000 chance)
> ...etc
> If there's a really good business reason for the uniqueness, this is enoug
h
> of a risk to make it worth enforcing, but you could update hundreds of
> thousands of records at a time without noticing any overlaps.
> Rob
>
> "Dan D." <DanD@.discussions.microsoft.com> wrote in message
> news:F8787F1F-4AC0-405C-9E8E-5ACF7841F11D@.microsoft.com...
>
>|||I wish I knew. This project was contracted out. There was no statement of
work, documentation, etc. by the original contractors. The project was takin
g
too long (surprise!) so it was brought in-house and another group of
contractors was hired to fix it.
I look through the code once in a while to see how other people code and to
learn.
--
Dan D.
"--CELKO--" wrote:

> What is this nightmare of poorly formatted insanely proprietary code
> supposed to do? Without a spec, it is pretty hard to answer your
> querstion. I have the feeling that this crap is not using a relatioanl
> key at all, but that it is randomly trying to construct an unverifiable
> exposed locator on the fly.
>|||Dan,
It sounds to me like you need to look through the business rules, and
probably get new contractors. :) If you can use more than 10 digits, then by
all means do that. I would actually suggest starting with the id number and
then using the large number padded to 10 digits. That way, you can guarantee
its uniqueness, plus you won't have 0 as the first character (because you
will need to pad the 10-digits to be sure it's unique - consider the case
where your checksum gives you a very small result).

> Can you tell me what how this part of the code works:
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
This just gets the top row from @.tblCompanyFranchise without having any
filter, and populates the variables @.Id, @.companyId and @.franchiseId. It's
basically a cursor without having a cursor. My guess is that your
contractors have read that cursors are bad practice, but instead of taking a
set-based approach, have simply altered the code to remove the cursor
declaration.
Rob
PS: Sorry for my silence over the past several hours - I'm in Australia.
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:A69B97BF-8B5F-4BFE-AD9E-573868DBBAD7@.microsoft.com...
> The pinid column is a varchar(30) so if the contractor was really worried
> about uniqueness, I don't know why he didn't use more of the id field. The
> id
> itself is also supposed to be unique so the chance of combining the
> checksum
> of newid() and all of the id field is pretty small.
> I ran your query and it took 6 seconds. The original code took 4 hours.
> Can you tell me what how this part of the code works:
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
> I interpret it to mean select the first record from @.tblCompanyFranchise
> where the @.id in @.tblCompanyFranchise equals [id] and where @.companyid
> equals
> companyid and where @.franchiseid equals franchiseid. But where does the
> value
> for [id], companyid and franchiseid come from?
> Thanks so much for your help Rob.
> --
> Dan D.
>
> "Rob Farley" wrote:
>|||:) Yup. I try to sleep at night occasionally.
"Stefan Berglund" <sorry.no.koolaid@.for.me> wrote in message
news:ges982dt67flvs05h9i7pjf0sja9ah6i0j@.
4ax.com...
> On Tue, 6 Jun 2006 11:46:47 +0930, "Rob Farley" <rob_farley@.hotmail.com>
> wrote:
> in <uVR#E9QiGHA.3904@.TK2MSFTNGP02.phx.gbl>
> Oh! - Have they been closed for several hours?
> --
> Stefan Berglund|||Yeah, we have a regular scheduled outage for maintenance. We shut down
the country for a few hours each night - didn't you get the memo?
*mike hodgson*
http://sqlnerd.blogspot.com
Stefan Berglund wrote:

>On Tue, 6 Jun 2006 11:46:47 +0930, "Rob Farley" <rob_farley@.hotmail.com>
>wrote:
> in <uVR#E9QiGHA.3904@.TK2MSFTNGP02.phx.gbl>
>
>Oh! - Have they been closed for several hours?
>--
>Stefan Berglund
>

Thursday, March 8, 2012

Convert string into sql date time

i have a sql statement that i created in code and it is sending a query to the database
when i dim the variable a datetime variable it says that it cant convert it
if i make the variable a varchar it works but it only returns one result when it should be returning about 10

here is the code


Public Function dbDGQSSearch(ByVal BatchID As String, ByVal CreatedBy As Integer, ByVal CreatedFor As Integer, ByVal DateCreatedMod As Integer, ByVal DateCreated As String, ByVal DateCompletedMod As Integer, ByVal DateCompleted As String, ByVal DateStartedMod As Integer, ByVal DateStarted As String, ByVal SearchType As Integer, ByVal Completed As Integer, ByVal PriorityMod As Integer, ByVal Priority As Integer, ByVal RemainingCallsMod As Integer, ByVal RemainingCalls As Integer, ByVal TotalCallsMod As Integer, ByVal TotalCalls As Integer, ByVal Bonus As Integer, ByVal Keyword1 As String, ByVal Keyword2 As String, ByVal Keyword3 As String, ByVal Keyword4 As String, ByVal Keyword5 As String)

Dim strQueSearch As String
strQueSearch = "SELECT tlkup_Rep.RepID, tlkup_Rep.PositionID, tlkup_Rep.RepFName, tlkup_Rep.RepLName, tlkup_Rep.RepPassword, tlkup_Rep.RepUserName, tlkup_Rep.RepFName + ' ' + tlkup_Rep.RepLName AS RepName, t_Que.QueID, t_Que.BatchID, t_Que.AdminID, t_Que.Manager, t_Que.BonusID, t_Que.QueCompleted, t_Que.QueDate, t_Que.QueNotes, t_Que.QuePriority, t_Que.QueQuantity, t_Que.QueStartDate, t_Que.Mail, t_Que.QueDateComplete, t_Que.QueTotal FROM t_Que INNER JOIN tlkup_Rep ON t_Que.Manager = tlkup_Rep.RepID AND t_Que.Manager = tlkup_Rep.RepID WHERE BatchID<>'' and BatchID<>'2' and BatchID<>'3' and BatchID<>'4' "

'Creates statement for selecting the add to batch data where the criteria appear
If BatchID <> "" Then

strQueSearch = strQueSearch + " and t_Que.BatchID= @.BatchID "
End If
If CreatedBy > 1 Then
strQueSearch = strQueSearch + " and t_Que.RepID =@.RepID "
End If
If CreatedFor > 1 Then
strQueSearch = strQueSearch + " and t_Que.Manager = @.Manager "
End If

If DateCreated <> "" Then
If DateCreatedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueDate >@.QueDate "
ElseIf DateCreatedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueDate <@.QueDate "
ElseIf DateCreatedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueDate =@.QueDate "
End If
End If

If DateCompleted <> "" Then
If DateCompletedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueDateComplete >@.QueDateComplete "
ElseIf DateCompletedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueDateComplete <@.QueDateComplete and t_Que.QueDateComplete >'1/1/1900' "
ElseIf DateCompletedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueDateComplete =@.QueDateComplete "
End If
End If

If DateStarted <> "" Then
If DateStartedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueStartDate >@.QueStartDate "
ElseIf DateStartedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueStartDate <@.QueStartDate "
ElseIf DateStartedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueStartDate =@.QueStartDate "
End If
End If

If SearchType = 0 Then
'Both
'strQueSearch = strQueSearch + " and t_Que.Mail=0 and t_Que.Mail=1 "
ElseIf SearchType = 1 Then
'Mail
strQueSearch = strQueSearch + " and t_Que.Mail=1 "
ElseIf SearchType = 2 Then
'Phone
strQueSearch = strQueSearch + " and t_Que.Mail=0 "
End If

If Completed = 0 Then
'Both
'strQueSearch = strQueSearch + " and t_Que.Mail=0 and t_Que.Mail=1 "
ElseIf Completed = 1 Then
'Yes
strQueSearch = strQueSearch + " and t_Que.QueCompleted=1 "
ElseIf Completed = 2 Then
'No
strQueSearch = strQueSearch + " and t_Que.QueCompleted=0 "
End If

If Priority > 0 Then
If PriorityMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QuePriority >@.QuePriority "
ElseIf PriorityMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QuePriority <@.QuePriority "
ElseIf PriorityMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QuePriority =@.QuePriority "
End If
End If
If RemainingCalls > 0 Then
If RemainingCallsMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueQuantity >@.QueQuantity "
ElseIf RemainingCallsMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueQuantity <@.QueQuantity "
ElseIf RemainingCallsMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueQuantity =@.QueQuantity "
End If
End If

If TotalCalls > 0 Then
If TotalCallsMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueTotal >@.QueTotal "
ElseIf TotalCallsMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueTotal <@.QueTotal "
ElseIf TotalCallsMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueTotal =@.QueTotal "
End If
End If

If Bonus > 1 Then
strQueSearch = strQueSearch + " and t_Que.BonusID =@.BonusID "
End If

If Keyword1 <> "" Then
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword1+'%' "
End If
If Keyword2 <> "" Then
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword2+'%' "
End If
If Keyword3 <> "" Then
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword3+'%' "
End If
If Keyword4 <> "" Then
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword4+'%' "
End If
If Keyword5 <> "" Then
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword5+'%' "
End If

'makes statement into sqlcommand
C.daQueSearch.SelectCommand.CommandText = strQueSearch

'var declaration
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.BatchID", SqlDbType.VarChar, 12))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Manager", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.RepID", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueDate", SqlDbType.VarChar, 20)) '<-- This is what,when i change to datetime, says it cant convert
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueStartDate", SqlDbType.VarChar, 20))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueDateComplete", SqlDbType.VarChar, 20))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QuePriority", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueQuantity", SqlDbType.BigInt))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueTotal", SqlDbType.BigInt))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.BonusID", SqlDbType.SmallInt))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword1", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword2", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword3", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword4", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword5", SqlDbType.VarChar, 50))

'data entry
C.daQueSearch.SelectCommand.Parameters("@.BatchID").Value = BatchID
C.daQueSearch.SelectCommand.Parameters("@.Manager").Value = CreatedBy
C.daQueSearch.SelectCommand.Parameters("@.RepID").Value = CreatedFor
C.daQueSearch.SelectCommand.Parameters("@.QueDate").Value = DateCreated
C.daQueSearch.SelectCommand.Parameters("@.QueStartDate").Value = DateStarted
C.daQueSearch.SelectCommand.Parameters("@.QueDateComplete").Value = DateCompleted
C.daQueSearch.SelectCommand.Parameters("@.QuePriority").Value = Priority
C.daQueSearch.SelectCommand.Parameters("@.QueQuantity").Value = RemainingCalls
C.daQueSearch.SelectCommand.Parameters("@.QueTotal").Value = TotalCalls
C.daQueSearch.SelectCommand.Parameters("@.BonusID").Value = Bonus
C.daQueSearch.SelectCommand.Parameters("@.Keyword1").Value = Keyword1
C.daQueSearch.SelectCommand.Parameters("@.Keyword2").Value = Keyword2
C.daQueSearch.SelectCommand.Parameters("@.Keyword3").Value = Keyword3
C.daQueSearch.SelectCommand.Parameters("@.Keyword4").Value = Keyword4
C.daQueSearch.SelectCommand.Parameters("@.Keyword5").Value = Keyword5

Try
C.ndConnection.Open()
C.daQueSearch.SelectCommand.ExecuteNonQuery()
Catch ex As Exception
lblMainError1.Text = err("dbDGQSSearch " + ex.Source, ex.Message, CurUsr)
lblMainError1.Visible = True
Finally
C.ndConnection.Close()
End Try

FillQSDG()' this fills the datagrid

End Function

does your above code work ? because you are building the search string conditionally but adding the parameters without checking the conditions...

for xample :


If BatchID <> "" Then
strQueSearch = strQueSearch + " and t_Que.BatchID= @.BatchID "
End If

you are appending to the sql stmt if batchid <> ""...but here


C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.BatchID", SqlDbType.VarChar, 12))

you are adding the parameter to the collection without any checks..

lets say the the user did not supply any id for the batchid...then the sql stmt wil not be appended with "and t_Que.BatchID= @.BatchID " part...but the parameter is still being added ...

do you get my point ?|||i get your point but it seems to work correctly
it is adding to the parameter collection but doesnt actually use it until it is in the statement.
it probably isnt proper but it does work|||just for kicks i changed it and it still did not work but the weird thing is it doesnt work even if there is no criteria entered.

what is weird is i used the cool little red dot program walkthrough thing and i stopped it right on the sql transaction and copied the command.text and pasted it into query analizer and it got the require results
But the data grid that it is outputting to only shows one record

This is the new code


Public Function dbDGQSSearch(ByVal BatchID As String, ByVal CreatedBy As Integer, ByVal CreatedFor As Integer, ByVal DateCreatedMod As Integer, ByVal DateCreated As String, ByVal DateCompletedMod As Integer, ByVal DateCompleted As String, ByVal DateStartedMod As Integer, ByVal DateStarted As String, ByVal SearchType As Integer, ByVal Completed As Integer, ByVal PriorityMod As Integer, ByVal Priority As Integer, ByVal RemainingCallsMod As Integer, ByVal RemainingCalls As Integer, ByVal TotalCallsMod As Integer, ByVal TotalCalls As Integer, ByVal Bonus As Integer, ByVal Keyword1 As String, ByVal Keyword2 As String, ByVal Keyword3 As String, ByVal Keyword4 As String, ByVal Keyword5 As String)
Dim strQueSearch As String
strQueSearch = "SELECT tlkup_Rep.RepID, tlkup_Rep.PositionID, tlkup_Rep.RepFName, tlkup_Rep.RepLName, tlkup_Rep.RepPassword, tlkup_Rep.RepUserName, tlkup_Rep.RepFName + ' ' + tlkup_Rep.RepLName AS RepName, t_Que.QueID, t_Que.BatchID, t_Que.AdminID, t_Que.Manager, t_Que.BonusID, t_Que.QueCompleted, t_Que.QueDate, t_Que.QueNotes, t_Que.QuePriority, t_Que.QueQuantity, t_Que.QueStartDate, t_Que.Mail, t_Que.QueDateComplete, t_Que.QueTotal FROM t_Que INNER JOIN tlkup_Rep ON t_Que.Manager = tlkup_Rep.RepID AND t_Que.Manager = tlkup_Rep.RepID WHERE BatchID<>'' and BatchID<>'2' and BatchID<>'3' and BatchID<>'4' "

'Creates statement for selecting the add to batch data where the criteria appear
If BatchID <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.BatchID", SqlDbType.VarChar, 12))
C.daQueSearch.SelectCommand.Parameters("@.BatchID").Value = BatchID
strQueSearch = strQueSearch + " and t_Que.BatchID= @.BatchID "
End If
If CreatedBy > 1 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.RepID", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters("@.RepID").Value = CreatedFor
strQueSearch = strQueSearch + " and t_Que.RepID =@.RepID "
End If
If CreatedFor > 1 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Manager", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters("@.Manager").Value = CreatedBy
strQueSearch = strQueSearch + " and t_Que.Manager = @.Manager "
End If

If DateCreated <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueDate", SqlDbType.VarChar, 20))
C.daQueSearch.SelectCommand.Parameters("@.QueDate").Value = DateCreated
If DateCreatedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueDate >@.QueDate "
ElseIf DateCreatedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueDate <@.QueDate "
ElseIf DateCreatedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueDate =@.QueDate "
End If
End If

If DateCompleted <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueDateComplete", SqlDbType.VarChar, 20))
C.daQueSearch.SelectCommand.Parameters("@.QueDateComplete").Value = DateCompleted
If DateCompletedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueDateComplete >@.QueDateComplete "
ElseIf DateCompletedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueDateComplete <@.QueDateComplete and t_Que.QueDateComplete >'1/1/1900' "
ElseIf DateCompletedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueDateComplete =@.QueDateComplete "
End If
End If

If DateStarted <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueStartDate", SqlDbType.VarChar, 20))
C.daQueSearch.SelectCommand.Parameters("@.QueStartDate").Value = DateStarted
If DateStartedMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueStartDate >@.QueStartDate "
ElseIf DateStartedMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueStartDate <@.QueStartDate "
ElseIf DateStartedMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueStartDate =@.QueStartDate "
End If
End If

If SearchType = 0 Then
'Both
'strQueSearch = strQueSearch + " and t_Que.Mail=0 and t_Que.Mail=1 "
ElseIf SearchType = 1 Then
'Mail
strQueSearch = strQueSearch + " and t_Que.Mail=1 "
ElseIf SearchType = 2 Then
'Phone
strQueSearch = strQueSearch + " and t_Que.Mail=0 "
End If

If Completed = 0 Then
'Both
'strQueSearch = strQueSearch + " and t_Que.Mail=0 and t_Que.Mail=1 "
ElseIf Completed = 1 Then
'Yes
strQueSearch = strQueSearch + " and t_Que.QueCompleted=1 "
ElseIf Completed = 2 Then
'No
strQueSearch = strQueSearch + " and t_Que.QueCompleted=0 "
End If

If Priority > 0 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QuePriority", SqlDbType.Int))
C.daQueSearch.SelectCommand.Parameters("@.QuePriority").Value = Priority
If PriorityMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QuePriority >@.QuePriority "
ElseIf PriorityMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QuePriority <@.QuePriority "
ElseIf PriorityMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QuePriority =@.QuePriority "
End If
End If

If RemainingCalls > 0 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueQuantity", SqlDbType.BigInt))
C.daQueSearch.SelectCommand.Parameters("@.QueQuantity").Value = RemainingCalls
If RemainingCallsMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueQuantity >@.QueQuantity "
ElseIf RemainingCallsMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueQuantity <@.QueQuantity "
ElseIf RemainingCallsMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueQuantity =@.QueQuantity "
End If
End If

If TotalCalls > 0 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.QueTotal", SqlDbType.BigInt))
C.daQueSearch.SelectCommand.Parameters("@.QueTotal").Value = TotalCalls
If TotalCallsMod = 0 Then
'>
strQueSearch = strQueSearch + " and t_Que.QueTotal >@.QueTotal "
ElseIf TotalCallsMod = 1 Then
'<
strQueSearch = strQueSearch + " and t_Que.QueTotal <@.QueTotal "
ElseIf TotalCallsMod = 2 Then
'=
strQueSearch = strQueSearch + " and t_Que.QueTotal =@.QueTotal "
End If
End If

If Bonus > 1 Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.BonusID", SqlDbType.SmallInt))
C.daQueSearch.SelectCommand.Parameters("@.BonusID").Value = Bonus
strQueSearch = strQueSearch + " and t_Que.BonusID =@.BonusID "
End If

If Keyword1 <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword1", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters("@.Keyword1").Value = Keyword1
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword1+'%' "
End If
If Keyword2 <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword2", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters("@.Keyword2").Value = Keyword2
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword2+'%' "
End If
If Keyword3 <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword3", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters("@.Keyword3").Value = Keyword3
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword3+'%' "
End If
If Keyword4 <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword4", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters("@.Keyword4").Value = Keyword4
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword4+'%' "
End If
If Keyword5 <> "" Then
C.daQueSearch.SelectCommand.Parameters.Add(New SqlParameter("@.Keyword5", SqlDbType.VarChar, 50))
C.daQueSearch.SelectCommand.Parameters("@.Keyword5").Value = Keyword5
strQueSearch = strQueSearch + " and t_Que.QueNotes like '%'+@.Keyword5+'%' "
End If

'makes statement into sqlcommand
C.daQueSearch.SelectCommand.CommandText = strQueSearch

Try
C.ndConnection.Open()
C.daQueSearch.SelectCommand.ExecuteNonQuery()
Catch ex As Exception
lblMainError1.Text = err("dbDGQSSearch " + ex.Source, ex.Message, CurUsr)
lblMainError1.Visible = True
Finally
C.ndConnection.Close()
End Try

FillQSDG()

|||you are declaring it as a function...whats the return type? what are you returning ?

Public Function dbDGQSSearch(ByVal BatchID As String, ByVal CreatedBy As Integer, ByVal CreatedFor As Integer, ByVal DateCreatedMod As Integer, ByVal DateCreated As String, ByVal DateCompletedMod As Integer, ByVal DateCompleted As String, ByVal DateStartedMod As Integer, ByVal DateStarted As String, ByVal SearchType As Integer, ByVal Completed As Integer, ByVal PriorityMod As Integer, ByVal Priority As Integer, ByVal RemainingCallsMod As Integer, ByVal RemainingCalls As Integer, ByVal TotalCallsMod As Integer, ByVal TotalCalls As Integer, ByVal Bonus As Integer, ByVal Keyword1 As String, ByVal Keyword2 As String, ByVal Keyword3 As String, ByVal Keyword4 As String, ByVal Keyword5 As String)...?

hth|||what is the question?
if it is because it is not returning anything, that is fine, that isnt what is wrong, it doesnt need to return anything.
if it is because it is excruciatingly long i know
but this doesnt help me a whole lot|||i asked those q's because i didnt understand what you are trying to do in the function...you have a select statement but you say executenonquery... which does not return any records..if you need the resultset you need to say execteReader

hth|||i changed it to executeREADER and it is still only returning one result to the datagrid.
and, if as i said before, i take the statement that it is going to the query and put it into the query analizer it will return the correct results|||sorry
being un observant can be very frustrating, i was filling the dataset with the wrong data adapter

Convert sql proc to a c# class?

Anyone have code to convert a sql proc to a C# class?

Specifially something to create the columns returned from the proc.

Thanks.I figured this out myself.

Just execute the proc in a sqldataadapter, fill a dataset, then loop thru the columns
while creating text output for a C# class.

Pretty simple.|||Are you referring to a code gen script? Can you elaborate on your request?

Saturday, February 25, 2012

convert of code from access to sql server

Hi
give code is in access wann to convert into SQL Server help me plz
SELECT PPCR_tbl_Form.PPCRID, PPCR_tbl_Form.StatusID,
DateValue(IIf(DLookUp("PPCRID","QS_PPCR_Approved_Latest","[PPCRID]= " &
PPCR_tbl_Form.PPCRID) Is
Null,[MinRevDate],QS_PPCR_Approved_Lates
t.LatestApprovalDate)) AS
FromDate, DateValue(IIf([PPCR_tbl_Form.StatusID] In
(14,16,17),[MaxRevDate],Now())) AS ToDate
FROM (PPCR_tbl_Form INNER JOIN QS_PPCR_MaxMin_RevDate ON
PPCR_tbl_Form.PPCRID=QS_PPCR_MaxMin_RevDate.PPCRID) LEFT JOIN
QS_PPCR_Approved_Latest ON
PPCR_tbl_Form.PPCRID=QS_PPCR_Approved_Latest.PPCRID
WHERE (((PPCR_tbl_Form.StatusID)<>1))
ORDER BY PPCR_tbl_Form.PPCRID;Sorry. You are going to have to provide DDL and what you are trying to do.|||"san" <skrupareliya@.gmail.com> wrote in message
news:1141430689.221902.287910@.j33g2000cwa.googlegroups.com...
> Hi
> give code is in access wann to convert into SQL Server help me plz
>
>
> SELECT PPCR_tbl_Form.PPCRID, PPCR_tbl_Form.StatusID,
> DateValue(IIf(DLookUp("PPCRID","QS_PPCR_Approved_Latest","[PPCRID]= " &
> PPCR_tbl_Form.PPCRID) Is
> Null,[MinRevDate],QS_PPCR_Approved_Lates
t.LatestApprovalDate)) AS
> FromDate, DateValue(IIf([PPCR_tbl_Form.StatusID] In
> (14,16,17),[MaxRevDate],Now())) AS ToDate
> FROM (PPCR_tbl_Form INNER JOIN QS_PPCR_MaxMin_RevDate ON
> PPCR_tbl_Form.PPCRID=QS_PPCR_MaxMin_RevDate.PPCRID) LEFT JOIN
> QS_PPCR_Approved_Latest ON
> PPCR_tbl_Form.PPCRID=QS_PPCR_Approved_Latest.PPCRID
> WHERE (((PPCR_tbl_Form.StatusID)<>1))
> ORDER BY PPCR_tbl_Form.PPCRID;
>
Hit the Books Online.
Replace IIF with CASE.
Replace DLookup with a scalar subquery.
Replace Now() with GetDate().
David

Friday, February 24, 2012

Convert money columns to update?

Hi Guys

I need your help again, I am try to update several columns and the data type is 'money'.

Below is the code I have used:

UPDATE CAT_Products
SET

UnitCost ='10.00',
UnitCost2 = '10.00',
UnitCost3 = '10.00',
UnitCost4 = '10.00',
UnitCost5 = '10.00',
UnitCost6 = '10.00'

WHERE ProductCode = '0008'

But it will not update, instead I get this error:

-----------------------------------------------------------

>[Error] Script lines: 1-9 --------
Disallowed implicit conversion from data type varchar to data type money, table 'dbo.CAT_Products', column 'UnitCost'. Use the CONVERT function to run this query.

More exceptions ... Disallowed implicit conversion from data type varchar to data type money, table '.dbo.CAT_Products', column 'UnitCost2'. Use the CONVERT function to run this query.

-----------------------------------------------------------

The error message indicates that I need to use the convert function. But the columns data type is set at 'money' not 'varcher' . So do I need to convert data type to 'varcher' in order to update and convert back to data type 'money' when update complete? Or do I need to indicate in the update statement that data type is already 'money'? I am not sure how I would either.

Thanks

try:

UPDATE CAT_Products
SET

UnitCost =convert(money,'10.00'),
UnitCost2 = convert(money,'10.00'),
UnitCost3 = convert(money,'10.00'),
UnitCost4 =convert(money,'10.00'),
UnitCost5 = convert(money,'10.00'),
UnitCost6 = convert(money,'10.00')

WHERE ProductCode = '0008'

|||

Hi jpazgier

Thank you for your reply and code.

I am pleased to say that your code worked first time.

A great help.

Cheers.

Convert IP Address to Long

Hi, can I use a SQL server Stored Procedure to convert an IP Address to Long?

In VB.NET I use the following code (hope that helps).


Private Function ConvertToLong(ByVal IPAddress As Object) As Object

Dim x As Integer
Dim Pos As Integer
Dim PrevPos As Integer
Dim Num As Integer

If UBound(Split(IPAddress, ".")) = 3 Then
' On Error Resume Next
For x = 1 To 4
Pos = InStr(PrevPos + 1, IPAddress, ".", 1)
If x = 4 Then Pos = Len(IPAddress) + 1
Num = Int(Mid(IPAddress, PrevPos + 1, Pos - PrevPos - 1))
If Num > 255 Then
ConvertToLong = "0"
Exit Function
End If
PrevPos = Pos
ConvertToLong = ((Num Mod 256) * (256 ^ (4 - x))) + ConvertToLong
Next
End If

End Function

Here's a UDF that should do what you are looking for.

Usage: SELECT dbo.fnStringIPToLongIP('192.168.0.1')


CREATE FUNCTION dbo.fnStringIPToLongIP (@.IPAddress AS varchar(15))
RETURNS bigint AS
BEGIN

DECLARE
@.x Integer,
@.Pos Integer,
@.PrevPos Integer,
@.Num Integer,
@.ConvertToLong bigint

SET @.ConvertToLong = 0

IF LEN(RTRIM(REPLACE(@.IPAddress,'.',''))) = LEN(RTRIM(@.IPAddress))-3
BEGIN
SET @.X = 1
SET @.PrevPos = 0
WHILE @.X <= 4
BEGIN
SET @.Pos = CHARINDEX('.',@.IPAddress,@.PrevPos + 1)
IF @.x = 4
SET @.Pos = Len(@.IPAddress) + 1

SET @.Num = SUBSTRING(@.IPAddress, @.PrevPos + 1, @.Pos - @.PrevPos - 1)
If @.Num > 255
BEGIN
SET @.ConvertToLong = '0'
SET @.X = 5
BREAK
END
SET @.PrevPos = @.Pos
SET @.ConvertToLong = ((@.Num % 256) * CAST(POWER(256,(4 - @.x)) AS bigint)) + @.ConvertToLong
SET @.X = @.X + 1
END
END

RETURN(@.ConvertToLong)

END

Terri|||Thanks a million!!!|||FYI...The EasyWay.NET


Dim lng As Long = System.Net.IPAddress.Parse("192.168.0.1").Address

Sunday, February 12, 2012

convert dynamically generated parameters list into stored proc

I have the following ASP code that builds part of the example SQL statement below (it's the same SQL as in my earlier thread here (http://www.dbforums.com/showthread.php?t=1214044) but a very different question):

if sFindTicketEventId > 0 then sSQL = sSQL & " AND [tblEvents].[id]=" & sFindTicketEventId
if sFindTicketStandId > 0 then sSQL = sSQL & " AND [tblStands].[id]=" & sFindTicketStandId

SELECT
[tblC].[id] AS CombinationID,
[tblC].[availability],
[tblC].[description],
[tblC].[price] AS combinationPrice,
[tblC].[combination_open],
[tblT].[TicketID] AS TicketID,
[tblT].[price] AS ticketPrice,
[tblT].[availability],
[tblT].[ticket_open],
[tblT].[quantity],
[tblT].[event_name],
[tblT].[event_open],
[tblT].[stand_name],
[tblT].[stand_open],
[tblT].[admission_start_date],
[tblT].[admission_end_date],
[tblT].[date_open],
[tblT].,
[tblT].,
[tblT2].[description],
[tblT2].[admin_description]
FROM(
SELECT
[tblCombinations].[id],
[tblTickets].[id] As TicketID, [tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
FROM [tblCombinations]
LEFT JOIN [tblCombinations_Tickets] ON [tblCombinations_Tickets].[combination_id] = [tblCombinations].[id]
LEFT JOIN [tblTickets] ON [tblCombinations_Tickets].[ticket_id] = [tblTickets].[id]
LEFT JOIN [tblEvents] ON [tblEvents].[id] = [tblTickets].[event_id]
LEFT JOIN [tblStands] ON [tblStands].[id] = [tblTickets].[stand_id]
LEFT JOIN [tblAdmissionDates] ON [tblAdmissionDates].[id] = [tblTickets].[admission_date_id]
LEFT JOIN [tblBookingDates] ON [tblBookingDates].[id] = [tblTickets].[booking_date_id]
LEFT JOIN [tblTicketConcessions] ON [tblTicketConcessions].[id] = [tblTickets].[ticket_concession_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMinQuantities] ON [tblBookingMinQuantities].[id] = [tblTickets].[booking_min_quantity_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMaxQuantities] ON [tblBookingMaxQuantities].[id] = [tblTickets].[booking_max_quantity_id]
LEFT JOIN [tblMemberships] ON [tblMemberships].[id] = [tblTickets].[membership_id]
WHERE 1=1
[B]AND [tblEvents].[id]=2
[B]AND [tblStands].[id]=3
--AND [tblAdmissionDates].[id]=@.admissionDateId
--AND [tblBookingDates].[id]=@.bookingDateId
--AND [tblTicketConcessions].[id]=@.concessionId
--AND [tblBookingMinQuantities].[id]=@.bookingMinQuantityId
--AND [tblBookingMaxQuantities].[id]=@.bookingMaxQuantityId
--AND [tblMemberships].[id]=@.membershipId
GROUP BY
[tblCombinations].[id],
[tblTickets].[id],
[tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
) as [tblT]
JOIN [tblCombinations] as [tblC] on [tblT].[id]=[tblC].[id]
LEFT JOIN [tblTickets] as [tblT2] on [tblT].[TicketID]=[tblT2].[id]

I want to turn this SQL into a stored proc; there are currently about 8 parameters that I want to pass into it. The field value for each will be either NULL or a positive integer, and the paramater will be passed in as an integer.

If the passed parameter value is a positive integer then it should return all records where the corresponding field value matches that integer. If the passed parameter is 0, it should return all rows regardless of whether the field value is an integer or NULL.

And I can't for the life of me figure out how to do it. Do I need an IF statement in there or something?

:confused:Hi
A common method is:
WHERE (MyField = @.MyParam OR @.MyParam = 0)
I read an article somewhere though that poohed poohed this as the optimiser can't use the index or something though.|||Well, seeing as my state of blissful ignorance safely censored your "optimiser" comment, I can happily report that the solution works great :) Thanks.