WHERE Clause Using Different Column Passed By Parameter
Jul 30, 2007
Hi all,
I'd think this is possible but I'm having trouble getting data returned from the query. Fields PART_NUMBER and INTERNAL_SKU exist in the SKU table. This will be inside a SP. If user passes 'PN' as first parameter then I'd need to have the WHERE clause by PART_NUMBER, if he passes 'SK' (or anything else for now) then the WHERE clause shold be by SKU.
Can't I just build the WHERE by replacing @SearchField with its value ? I've looked up the CASE statement but I don't think it does what I need.
DECLARE @strSearchType varchar(2)
DECLARE @strSearchValue varchar(15)
DECLARE @SearchField varchar(15)
set @strSearchType = 'PN'
set @strSearchValue = '1234567'
IF @strSearchType = 'PN'
begin
set @SearchField = 'PART_NUMBER'
end
ELSE
begin
set @SearchField = 'INTERNAL_SKU'
end
SELECT
SKU as 'SKU',
PART_NUMBER as 'PartNumber',
DESCRIPTION as 'Description'
FROM SKUs
WHERE @SearchField = @strSearchValue
FOR XML PATH('SKU'), ROOT('Response')
Thanks,
ST
View 4 Replies
ADVERTISEMENT
Sep 20, 2014
In a SPROC I am creating, is there a way to use a columnName as a parameter and then do a filter on that based on a second parameter such as @columnValue ?
So instead of having to construct the WHERE clause or doing a bunch of IF statements to see what the column name is from the parameter and doing a query based upon that, is there a way to tell it to do a WHERE clause where @columnName = @columnValue ?
I do not want to use dynamic SQL string concatenation...
View 5 Replies
View Related
Feb 19, 2007
Hello,
since a couple of days I'm fighting with RS 2005 and the Stored Procedure.
I have to display the result of a parameterized query and I created a SP that based in the parameter does something:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [schema].[spCreateReportTest]
@Name nvarchar(20)= ''
AS
BEGIN
declare @slqSelectQuery nvarchar(MAX);
SET NOCOUNT ON
set @slqSelectQuery = N'SELECT field1,field2,field3 from table'
if (@Name <> '')
begin
set @slqSelectQuery = @slqSelectQuery + ' where field2=''' + @Name + ''''
end
EXEC sp_executesql @slqSelectQuery
end
Inside my business Intelligence Project I created:
-the shared data source with the connection String
- a data set :
CommandType = Stored Procedure
Query String = schema.spCreateReportTest
When I run the Query by mean of the "!" icon, the parameter is Prompted and based on the value I provide the proper result set is displayed.
Now I move to "Layout" and my undertanding is that I have to create a report Paramater which values is passed to the SP's parameter...
So inside"Layout" tab, I added the parameter: Name
allow blank value is checked and is non-queried
the problem is that when I move to Preview -> I set the value into the parameter field automatically created but when I click on "View Report" nothing has been generated!!
What is wrong? What I forgot??
Thankx for any help!
Marina B.
View 3 Replies
View Related
Nov 19, 2007
I have tested the following code, and it works for me:
DECLARE @XML XML
SET @XML = '
<DocumentElement>
<data>
<item code="ABCDEFG" quantity="1" sort="0" />
<item code="XCFVGBF" quantity="1" sort="0" />
<item code="ABCDEFG" quantity="10" sort="0" />
</data>
</DocumentElement>'
SELECT SUM(x.qty * ISNULL(p.price_mn,0))
FROM (SELECT [Code] = A.A.value('@code','varchar(20)'),
[Qty] = A.A.value('@quantity','INT')
FROM @xml.nodes('/DocumentElement/data/item') AS A(A)) X
LEFT JOIN productprice_t P ON p.code_id = x.code
The question is, how can I do this if the XML is in a different format & doesn't use any attributes?
So it looks like this (which I'm getting from an ADO.Net datatable using .WriteXML):
<DocumentElement>
<data>
<code>ABCDEFG</mercurycode>
<quantity>1</quantity>
<sort>0</sort>
</data>
<data>
<mercurycode>XCDFEG</mercurycode>
<quantity>2</quantity>
<sort>0</sort>
</data>
<data>
<code>ABCDEFG</mercurycode>
<quantity>10</quantity>
<sort>0</sort>
</data>
</DocumentElement>
View 5 Replies
View Related
Mar 19, 2007
I am quite new to SSRS and am having some difficulties in trying to develop a new report via Business Intelligence Studio based on a stored procedure which requires the input of 1 parameter, and also has an optional parameter which I default to NULL in the sproc.
When I create my dataset I select the given sproc I want and when I attempt to execute it, I am prompted for the parameters the sproc expects.
However, when I enter a value in the dialog for the required Parameter I get a SQL error indicating that the parameter the sproc expects was not supplied. I have profiled the call and see the attempt to execute the sproc, but no parameter value.
Can some one tell me why the value I enter is not being passed to the sproc in my database ? Is there some special syntax that I need to use ?
I have scanned a number of sites & through the books I have and can't find anything on this. From what I have read, when I exec my sproc the parameters get recongnized & I can just enter my values. This doesn't seem to be the case.
Any help and/or suggestions are appreciated !!!
Thanks.
View 8 Replies
View Related
Nov 30, 2007
I have a requirement where, I need to get the value of parameter from a query string of url and use it in my report.
Ex:- http://www.mysite.com?name=bobby
From the above url, I have to take the value of name and be able to use it in my report query or assign to a parameter.
Please let me know, how can I acheive this.
View 1 Replies
View Related
Jan 28, 2008
I have a boolean parameter on my report that the user will enter. Currently, it shows as an option button with True/False beside each option as the words used. Is it possible to have a check box instead of an option button for the user instead?
Thanks in advance!
View 3 Replies
View Related
Oct 18, 2006
I am trying to pass multiple values as parameters into my update command:UPDATE tblUserDetails SET DeploymentNameID = 102 WHERE ((EmployeeNumber IN (@selectedusersparam)));I develop my parameter (@selectedusersparam) using the following subroutine: Private Sub btnAddUsersToDeployment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddUsersToDeployment.ClickDim iVal As Integer = 0Dim SelectedCollection As StringSelectedCollection = ""If (lsbUsersAvail.Items).Count > 1 ThenFor iVal = 0 To lsbUsersAvail.Items.Count - 1If lsbUsersAvail.Items(iVal).Selected = True ThenSelectedCollection = SelectedCollection & "," & lsbUsersAvail.Items(iVal).ValueEnd IfNextSelectedCollection = Mid(SelectedCollection, 2, Len(SelectedCollection))Session.Item("SelectedCollectionSession") = SelectedCollectionSqlDataSource4.Update()ltlUsersMessage.Text = String.Empty 'UPDATE tblUserDetails SET DeploymentNameID = @DeploymentNameIDparam WHERE (EmployeeNumber IN (@selectedusersparam))'SqlDataSource4.UpdateCommand = "UPDATE tblUserDetails SET DeploymentNameID = @DeploymentNameIDparam WHERE (EmployeeNumber IN (" + SelectedCollection + ")"ElseltlUsersMessage.Text = "Select users before adding to deployment. Hold Control for multiselect"End IfEnd SubFor some reason the query does not pass the parameters which are "21077679,22648722,22652940,21080617" into the queryI don't understand why.
View 4 Replies
View Related
Apr 9, 2008
I am using two drop downs, like so:
<asp:DropDownList ID="ChurchStateDrop" runat="server" DataSourceID="ChurchStateDropData" DataTextField="State" DataValueField="State" AutoPostBack="True" onselectedindexchanged="ChurchStateDrop_SelectedIndexChanged" AppendDataBoundItems="True"> <asp:ListItem Value="?????" Selected="True" Text="All States" /></asp:DropDownList>
<asp:DropDownList ID="ChurchCityDrop" runat="server" DataSourceID="ChurchCityDropData" DataTextField="City" DataValueField="City" AutoPostBack="True" onselectedindexchanged="ChurchCityDrop_SelectedIndexChanged" AppendDataBoundItems="True"> <asp:ListItem Value="?????" Selected="True" Text="All Cities" /></asp:DropDownList>
I have ????? in the value fields because I don't know what value needs to be passed to negate filtering (to choose all). The Dropdowns have the following SQLDatasources:<asp:SqlDataSource ID="ChurchStateDropData" runat="server" ConnectionString="<%$ ConnectionStrings:tceDatabaseOnlineSQLConnection %>" SelectCommand="SELECT DISTINCT [State] FROM [ChurchView]" DataSourceMode="DataReader"></asp:SqlDataSource>
<asp:SqlDataSource ID="ChurchCityDropData" runat="server" ConnectionString="<%$ ConnectionStrings:tceDatabaseOnlineSQLConnection %>" SelectCommand="SELECT DISTINCT [City] FROM [ChurchView] WHERE ([State] = @State)" DataSourceMode="DataReader"> <SelectParameters> <asp:ControlParameter ControlID="ChurchStateDrop" Name="State" PropertyName="SelectedValue" Type="String" /> </SelectParameters></asp:SqlDataSource>
Now, lets say I wanted to pass a value to the WHERE statement in ChurchCityDropData to coincide with 'All States', what would I replace value="??????" with? Now you may think I'm crazy to do such a thing, but this actually has to do with adding a Denomination Dropdown to show Denominations from all states or all cities. I will figure out the best logic for that later, I just want to know the wildcard to pass to the parameter to choose all states (negate filtering).
View 3 Replies
View Related
Jul 23, 2005
I am new to sql and very familiar with access. I am using a verylarge database(130M records) in ms sql2000 and think I need to frontend it with access for reports and forms, etc..I have some questions:1) Is there a way in SQL to prompt a user for input at the running ofa query like the [what is your name] construct in an access query?2) I can't seem to create calculated fields in a view in sql. Inaccess I put "total:=hours*rate" and a new column would be createdwhich would contain the total.3) I normally would create a form in access from which the accessqueries would pull their variables and then insert those variables inthe queries or reports, etc. How would this be accomplished usingsql.4) Lastly and probably most basic. How does a "real" sql developercreate reports and forms to interact with the enduser? I am usingaccess as a front end, but am open to suggestions.Thanks,Brad
View 1 Replies
View Related
Jun 4, 2007
I have the follwoing stored procedure:ALTER procedure [dbo].[up_GetExecutionContext](@ExecutionGUID int = null) asbeginset nocount ondeclare@s varchar(500)declare @i intset @s = ''select @s = @s + EventType + ','-- Dynamically build the list ofeventsfrom(select distinct top 100 percent [event] as EventTypefrom dbo.PackageStepwhere (@ExecutionGUID is null or PackageStep.packagerunid =@ExecutionGUID)order by 1) as xset @i = len(@s)select case @iwhen 500 then left(@s, @i - 3) + '...'-- If string is too long thenterminate with '...'else left(@s, @i - 1) -- else just remove the final commaend as 'Context'set nocount offend --procedureGOWhen I run this and pass in a value of NULL, things work fine. When Ipass in an actual value (i.e. 15198), I get the following message:Invalid length parameter passed to the SUBSTRING function.There is no SUBSTRING being used anywhere in the query and thedatatypes look okay to me.Any suggestions would be greatly appreciated.Thanks!!
View 2 Replies
View Related
Mar 1, 2007
I have a SP that inserts data into a table with an identity column I want to get that id and use it in my response.redirect however I keep getting 0 back instead of the identity. Relevent Sql 2005 Declare @NEWEMPID int --after an insert happens in sqlSet @NEWEMPID= SCOPE_IDENTITY()--last thing in my sqlReturn @NEWEMPID Or I tried NEWEMPID as an output parameter VB.Net Dim retValParam As New SqlParameter("@NEWEMPID", SqlDbType.Int) retValParam.Direction = ParameterDirection.ReturnValue'execute the sqldatasource insert command
sqlEmpNewEmp.Insert()
Dim EmpIDVar As Integer = Convert.ToInt32(retValParam.Value) Response.Redirect("http://www.mysite.com?EMPID=" + Server.HtmlEncode(EmpIDVar)) sqlEmpNewEmp.InsertParameters.Clear()
View 8 Replies
View Related
Aug 13, 2007
Hi there when i tried to execute the following query in sql server
select au_fname,
SUBSTRING(P1.au_lname, CHARINDEX('/', P1.au_lname) + 1,
CHARINDEX('=', P1.au_lname, 1)-3)AS [Full Name]
from authors as P1
i will get the error like
"Invalid length parameter passed to the substring function."
If i remove -3 from there it works fine...
Please can anyone clarify this issue.
Thank You.
pavan
View 3 Replies
View Related
May 27, 2015
I have a requirement to show the parent value which is passed and also all the leaf member details in MDX. For example in Adventure works, if I pass Bikes as the value in MDX, the results should display Bikes along with All the child member names as a measure value in SSAS MDX. I only have one hierarchy with Product Category-> Subcategory-> Product.
Â
I am trying to use the following MDX but I am getting all the members. I need to get only Bikes in my report.
Â
WITH MEMBER [Prod_Passed] AS SETTOSTR(AXIS(1))
MEMBER [Prod_Child] AS DESCENDANTS ([Dim Product].[Hierarchy].CURRENTMEMBER,,LEAVES).item(0).NAME
MEMBER [Child_Value] AS ([Dim Product].[Hierarchy].CURRENTMEMBER,[Measures].[Sales Amount])
SELECT [Dim Product].[Hierarchy].[Product Category].&[1] * [Dim Product].[Product Key].[Product Key].MEMBERS ON ROWS,
{[Measures].[Sales Amount],[Prod_Passed],[Prod_Child],[Child_Value]} ON COLUMNS FROM
[AdvWorks]
View 10 Replies
View Related
Nov 12, 2004
Does anyone know what the above error message means?
View 4 Replies
View Related
Oct 7, 2014
How can I compute the biweekly periods when a date is passed in as a parameter, for example if the user enters 9/12/2014 I should get:
Friday /2nd half9/12/2014
Saturday9/13/2014
Sunday9/14/2014
Monday9/15/2014
Tuesday9/16/2014
Wednesday9/17/2014
Thursday9/18/2014
Friday/1st half 9/19/2014
Friday/2nd half9/19/2014
Saturday9/20/2014
Sunday9/21/2014
Monday9/22/2014
Tuesday9/23/2014
Wednesday 9/24/2014
Thursday9/25/2014
Friday/1st half 9/26/2014
View 2 Replies
View Related
Mar 3, 2014
I have a sql job which will execute the below stored proc.
Basically it Refresh the data by truncating the tables and using BCP to import the data. Job was running fine but today got a error message.
Invalid length parameter passed to the substring function. [SQLSTATE 42000] (Error 536). The step failed.
USE [database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Refresh_tables]
[Code] ......
View 2 Replies
View Related
Feb 1, 2008
Hi,
I was trying to execute the following query.
select substring(ISNULL(CAST(FullAdress AS NVARCHAR(MAX)),''),1,charindex(',',ISNULL(CAST(FullAdress AS NVARCHAR(MAX)),''))-1) from tbl_lrf_company_details_with_codes
but i am getting the error as "Invalid length parameter passed to the SUBSTRING function."
Please advice
Thanks In advance
View 4 Replies
View Related
May 27, 2008
SELECT
C.Description,
SUBSTRING (
(CONVERT (VARCHAR (255), D.CurrentXmlValue)), --expression
(CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue)) + 1), --start
( (LEN (CONVERT (VARCHAR (255), D.CurrentXmlValue))) -
(CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue))*2) - 1
)--length
) AS Version
FROM
:
:
WHERE
:
:
This does not work while
:
:
--SUBSTRING (
(CONVERT (VARCHAR (255), D.CurrentXmlValue)) as expression, --expression
(CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue)) + 1) as start, --start
( (LEN (CONVERT (VARCHAR (255), D.CurrentXmlValue))) -
(CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue))*2) - 1
) as length --length
--) AS Version
:
:
works!!
I get
Msg 536, Level 16, State 5, Line 2
Invalid length parameter passed to the SUBSTRING function.
Error.
Any idea why i am getting this??
I am trying to get rid of xml tags in the column.
Thanks,
View 4 Replies
View Related
Nov 16, 2004
I am not sure about the architecture of the Issue Tracker and hence not sure if it applies here. But I will post in any case and wait for users on this forums comments as well.
===========Earlier post==================
This question is regarding the architecture of TimeEntry.
In some programs it builds an arrayList for Master-detail type of relationship and when user is ready to save it by clicking 'submit' it build a variable with pipe delimited fields.
This is then passed to a sql query.
This to me does not seem to be an efficient manner. Because the max character is 1500 chars as parameter to SQL query.
I was wondering if instead I could store it as an XML and then use the XML to import in to SQL.
Any ideas is greatly appreciated, I am running in to problems where my variable construct does increase to more than 1500 chars. Any thoughts are much appreciated in this regards.
Regards,
MillenniumIte.
View 2 Replies
View Related
Sep 29, 2015
Currently i am using SQL Server 2012 Import/Export Wizard to upload data to sql tables manually. However i was trying to write a procedure to update that table. and on the time of execution, if i can pass excel. Is there any way to pass excel to stored procedure parameter?
View 1 Replies
View Related
Dec 1, 2015
is it possible to identify which value is causing me the above error message and how to resolve it,These are for British postcodes.
create table #tmp (postcode varchar(200) NULL)
insert into #tmp values ('NULL')
insert into #tmp values ('-')
insert into #tmp values ('.')
insert into #tmp values ('0L6 7TP')
insert into #tmp values ('AB10 1WP')
insert into #tmp values ('AB51 5HH')
[code]...
This is the main query
select postcode,LEFT([Postcode], CHARINDEX(' ',[Postcode]) - 1)
from #tmp
order by Postcode
drop table #tmp
View 4 Replies
View Related
Sep 28, 2007
Hi,
I am using a simple procedure to pivot results (found in another forum and adapted it). It is done on SQL Server 2005 server with all service packs. Procedure:
**************
ALTER Procedure [dbo].[EthnicityPivot] @StDate as Datetime, @EndDate as Datetime
as
begin
DECLARE @Teams varchar(2000)
truncate table ForEthnicPivot
INSERT INTO ForEthnicPivot
SELECT DISTINCT COUNT(ID), Team, Ethnicity
FROM dbo._EthnicityByTeamEpisode
where Startdate between @StDate and @EndDate
GROUP BY Ethnicity, Team
SET @Teams = ''
--// Get a list of the pivot columns that are important to you.
SELECT @Teams = @Teams + '[' + Team + '],'
FROM (SELECT Distinct Team FROM ForEthnicPivot) Team
--// Remove the trailing comma
SET @Teams = LEFT(@Teams, LEN(@Teams)-1)
--// Now execute the Select with the PIVOT and dynamically add the list
--// of dates for the columns
EXEC( 'SELECT * FROM ForEthnicPivot PIVOT (SUM(countID) FOR Team IN (' + @Teams + ')) AS X' )
end
************
I can call the function:
exec EthnicityPivot '01/01/2007','09/09/2007'
and it works fine in SQL analyzer, but when I want to use it in Visual Studio in a new report I am getting this error
message:
There is an error in the query. Invalid length parameter passed to the SUBSTRING function. Incorrect syntax near ')'.
Anyone had similar error and sorted it?
Cheers
Polda
View 4 Replies
View Related
May 28, 2015
I have a procedure that calls a SVF to convert an xmldocument. The ultimate purpose is to update the xml in a column in a multi-million row table. The xml is stored as varchar(MAX), it was supposed to carry any type of text, initially at least.
My question is: why is the xml-parsing performed inside the function much slower when i pass the xmldocument as type xml than when it is passed as varchar(MAX) and the CAST to xml is within the function? Does processing the xml input parameter in SlowFunction involve expensive crossing of some context border?
The two versions of the SVF (they return the rowcount in this simplified example):
CREATE FUNCTION [dbo].[FastFunction]
(
@inDetaljerText varchar(MAX)
)
RETURNS int
[Code] ....
The two versions of the SP
CREATE PROCEDURE [dbo].[FastProcedure]
AS
BEGIN
SET NOCOUNT ON;
select
dbo.FastFunction(al.Detaljer)
[Code] ....
View 2 Replies
View Related
Oct 9, 2006
Hi,
I am new at sql 2000 and 2005, I have created a package in 2005 which I am trying to execute on a daily bases by creating a job. At first because of security issues the job would not execute. Hence, I had to create a credential and a proxy to run the job with sa account. Now it is giving me this error,
€œSQLServer Error: 536, Invalid length parameter passed to the SUBSTRING function. €œ
Through research I have no clue as what I need to do, or where to look.
The package runs without error when I execute the package itself.
Any help is greatly appreciated.
Thanks,
Lori
View 1 Replies
View Related
Nov 28, 2005
Hi
i got errro mess "Invalid length parameter passed to the substring function" from this below. Anyone how can give me a hint what cause this, and how i can solve it? if i remove whats whitin thoose [] it works, i dont use [] in the code :)
colums:
VLF_InfectionDestination is nvarchar 254
SELECT TOP 10 tb_AVVirusLog.VLF_VirusName, COUNT(tb_AVVirusLog.VLF_VirusName) AS number
FROM tb_AVVirusLog INNER JOIN
__CustomerMachines002 ON tb_AVVirusLog.CLF_ComputerName = __CustomerMachines002.FalseName
WHERE (CONVERT(varchar, tb_AVVirusLog.CLF_LogGenerationTime, 120) BETWEEN @fyear + @fmonth + @fday AND @tyear + @tmonth + @tday) AND
(__CustomerMachines002.folder_id = @folderId) [OR
(CONVERT(varchar, tb_AVVirusLog.CLF_LogGenerationTime, 120) BETWEEN @fyear + @fmonth + @fday AND @tyear + @tmonth + @tday) AND
(tb_AVVirusLog.VLF_InfectionDestination LIKE N'%@%')]
GROUP BY tb_AVVirusLog.VLF_VirusName
HAVING (NOT (tb_AVVirusLog.VLF_VirusName LIKE N'cookie'))
ORDER BY COUNT(tb_AVVirusLog.VLF_VirusName) DESC
View 7 Replies
View Related
Jul 22, 2015
when I am trying to perform below query,
Â
 INSERT INTO EMPLOYEE
  SELECT TOP 100 *
 FROM EMPLOYEE_LANDING;
I am getting Invalid length parameter passed to the LEFT or SUBSTRING function.
View 3 Replies
View Related
May 4, 2015
I'm trying to replace a view with stored procedure for faster performance. the View is called by end user using a query as below, I need to pass the date as parameter for sp to execute with quotes for it to execute with correct results. Â I tried to pass the date as parameter but could not execute stored procedure with correct results. Is there any way to put quotes around returned date from sub query :Â
Execute statement is like
Exec dbo.storedProc1Â select max(date) from table
I need to pass the above as :
Exec dbo.storedProc '2015-03-24'Â .
Somehow passing the date as parameter is giving me empty result set.
View 2 Replies
View Related
Nov 12, 2003
An application I developed normally works great, but it seems that when processing a certian record (and none of the others so far), SQL Server throws this error:
"Invalid length parameter passed to the substring function."
Here's the code in question:
orderConnection.Open()
orderReader = orderCommand.ExecuteReader()
setControls(orderReader)
...
Private Sub setControls(ByVal dr As SqlDataReader)
If (dr.Read()) Then '<--*******problem line*******
The SqlDataReader (orderReader) doesn't blow up or anything until I call .Read() (and, as mentioned, this problem only occurs for one order). What could be happening here?
View 3 Replies
View Related
Jul 20, 2005
Example, suppose you have these 2 tables(NOTE: My example is totally different, but I'm simply trying to setupthe a simpler version, so excuse the bad design; not the point here)CarsSold {CarsSoldID int (primary key)MonthID intDealershipID intNumberCarsSold int}Dealership {DealershipID int, (primary key)SalesTax decimal}so you may have many delearships selling cars the same month, and youwanted a report to sum up totals of all dealerships per month.select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',sum(cs.NumberCarsSold) * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDMy question is, is there a way to achieve something like this:select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',TotalCarsSoldInMonth * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDNotice the only difference is the 3rd column in the select. Myparticular query is performing some crazy math and the only way I knowof how to get it to work is to copy and past the logic which isgetting out way out of hand...Thanks,Dave
View 5 Replies
View Related
May 14, 2008
2 examples:
1) Rows ordered using textual id rather than numeric id
Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
order by
v.id
Result set is ordered as: 1, 11, 2
I expect: 1,2,11
if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
2) SQL server reject query below with next message
Server: Msg 169, Level 15, State 3, Line 16
A column has been specified more than once in the order by list. Columns in the order by list must be unique.
Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
cross join (
select 1 id
union select 2 id
union select 11 id
) u
order by
v.id
,u.id
Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
It reproducible on
Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
and
Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
In both cases database collation is SQL_Latin1_General_CP1251_CS_AS
If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.
Could someone clarify - is it bug or expected behaviour?
View 12 Replies
View Related
Oct 20, 2006
I am trying to do a 'WHERE IN' clause by taking the value of a paremeter and using it as the value in the WHERE IN clause such as: DECLARE @parm NVARCHAR(1000) = 'IBM, MOT, MSFT'SELECT * FROM SomeStockTable WHERE TickerSymbol IN (@parm)I would like to avoid using an EXEC statement and string-building this whole query, since that is ugle and hard to maintain.ANy ideas? TYVM
View 1 Replies
View Related
Aug 22, 2007
I have posted this question in the MSDN SSRS forum, but have had no luck. I'm hoping someone can give me a definite yes or no if this is possible...
I want to be able to define a parameter for a report that will represent the entire where clause.
E.g. the report's dataset will be:
SELECT name, phone FROM person WHERE @whereclause
Has anyone accomplished this?
View 4 Replies
View Related