Select Alias -- Invalid Column Name
Hi,
I got 'Invalid Column Name NewCol1' when I query the following:
Select col1, col2, (some calculation from the fields) as NewCol1,
(some calculation from the fields) as NewCol2,
NewCol1 = NewCol2 from
Table1 inner join Table2 inner join Table3....
Where
.....
Basically, I want to find out if NewCol1 = NewCol2 after the
calculation
Any advice?
Thanks in advance. Your help would be greatly appreciated.
Wanda
View Complete Forum Thread with Replies
Related Forum Messages:
Error Invalid Column Name (In Sqlserver 2005) While Giving Alias Column Name
ALTER procedure [dbo].[MyPro](@StartRowIndex int,@MaximumRows int) As Begin Declare @Sel Nvarchar(2000)set @Sel=N'Select *,Row_number() over(order by myId) as ROWNUM from MyFirstTable Where ROWNUM Between ' + convert(nvarchar(15),@StartRowIndex) + ' and ('+ convert(nvarchar(15),@StartRowIndex) + '+' + convert(nvarchar(15),@MaximumRows) + ')-1' print @Sel Exec Sp_executesql @Sel End --Execute Mypro 1,4 --->>Here I Executed Error Select *,Row_number() over(order by myId) as ROWNUM from MyFirstTable Where ROWNUM Between 1 and (1+4)-1 Msg 207, Level 16, State 1, Line 1 Invalid column name 'ROWNUM'. Msg 207, Level 16, State 1, Line 1 Invalid column name 'ROWNUM Procedure successfully created but giving error while Excuting'. Please anybody give reply Thanks
View Replies !
SELECT Column Aliases: Refer To Alias In Another Column?
Using SQL Server 2000. How can I refer to one alias in another column?E.g., (this a contrived example but you get the idea)SELECT time, distance, (distance / time) AS speed, (speed / time) AS acceleration FROM dataNote how the speed alias is used in the definition of acceleration alias but this doesn't seem to work.
View Replies !
SELECT Column Aliases: Refer To Alias In Another Column?
Using SQL Server 2000. How can I refer to one alias in another column? E.g., (this a contrived example but you get the idea) SELECT time, distance, (distance / time) AS speed, (speed / time) AS acceleration FROM data Note how the "speed" alias is used in the definition of "acceleration" alias but this doesn't work.
View Replies !
Is It Possible To Re-reference A Column Alias From A Select Clause In Another Column Of The Same Select Clause?
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 Replies !
Using Column Alias In SELECT (was &"Asking&")
Hi, I have a question. select name, count, 1 Aa c1, 2 as c2, c1+c2 As total from table1 From this example, the program will give out error message, c1, and c2 are invalid columns. In MS Access, it works. But, SQL query Analayer doesn't work this statement. So, does query analayzer handle this case? Thanks.
View Replies !
Column Alias
Hello everyone. I was wondering if there is a way that you can set the alias name of a column to a value that resides in another table instead of the alias being a static value that you type in. If anyone has any ideas on ho i can accomplish this i would greatly appreciate it.
View Replies !
Order By Column Alias
I'm using SQL Server 2005 and are having some troubble with sorting a paged result set. I'm using the OVER Clause to achieve the sorting and paging and have the following query:1 WITH ProjectList AS 2 ( 3 SELECT 4 Id, 5 Name, 6 Created, 7 (SELECT COUNT(*) FROM UserProjects WHERE ProjectId = p.Id) AS NumberOfUsers, 8 ROW_NUMBER() OVER (ORDER BY Id) AS 'RowNumber' 9 FROM Projects p 10 ) 11 SELECT * 12 FROM ProjectList 13 WHERE RowNumber BETWEEN 50 AND 60; This works fine, and give me the results i want. The problem occurs when I want to sort by "NumberOfUsers" which is the results of a sub query.When i say "ORDER BY NumberOfUsers" instead of Id on line 8, I get the following error: Msg 207, Level 16, State 1, Line 10Invalid column name 'NumberOfUsers'. I read this in the documentation: When used in the context of a ranking window function, <ORDER BY Clause> can only refer to columns made available by the FROM clause. An integer cannot be specified to represent the position of the name or alias of a column in the select list. <ORDER BY Clause> cannot be used with aggregate window functions. So this means that what I'm trying to do is not possible. How can I then sort by NumberOfUsers? Is there any other way to achieve this
View Replies !
Use Column Alias In Another Calculation
Is there a way to use a column alias in an another calculation within thesame query? Since I am using some long and complex logic to compute total1and total2, I don't want to repeat the same logic to compute the ratio ofthose two columns. I know that I can do a nested query, but that seems toolengthy as well since I actually have many, many columns.selecttotal1 = sum(case(long complex logic)),total2 = sum(case(another long complex logic)),ratio = total1/total2
View Replies !
Column Alias In Views
Hi All, I am currently transferring my Access application to SQL Server. Access allows you to declare and use aliases in the query at the same time. e.g. Select field1 as Alias1, field2 as Alias2, Alias1 & " " & Alias2 as Alias3 from table1; In Access the above query will execute perfectly, no problem. However in SQL Server, if you try to run the same query it will give an error "Invalid column name Alias1" meaning that SQL Server is searching for Alias1 as a field in the table, not as an alias from the query. My question is does SQL Server have a facility to declare and use alias directly as in Access and if no, is there a workaround? Thanks for your time. Regards: Prathmesh
View Replies !
Column Name Alias Concatenation
I have a web application where I would like to return a dynamic column name using aliasing. below is an example: select hours as 'Fri<BR>' + cast(Day(getDate()) as varchar(2)) from todayshours I get an error trying to do concatenation as part of the alais. Any ideas? Luke lgraunke AT 4invie.com
View Replies !
Finding Real Name For Column Alias
Not sure if this can be done, but you are a clever bunch. I am looking for a way (preferably through a stored procedure) to return the original column name for an aliased cloumn. For example, I have a table view like: "SELECT id, firstname, lastname, qty as Amount FROM tblTeam" Returned columns are id, firstname, lastname, Amount. I would like to look up the results returned by the view, and get a list of the ORIGINATING columns (eg. id, firstname, lastname, qty) from the returned data. I am using php script to run stored proc. Thanks.
View Replies !
Multi Column Subquery? W/ Alias
What I need to do is to create 3 columns with 3 different aliases from the same table that will return all the values during the following conditions: when pricelist = 1 when pricelist = 2 when pricelist = 3 pricelist -------- 1 2 3 Price -------- 912 -- (linked with 1) 234 -- (linked with 3) 56 -- (linked with 2) 3245 -- (linked with 3) 234 -- (linked with 1) 65 -- (linked with 2) these 2 columns are in the same table^^ so what i want my query to generate is: Price1 -------- 912 234 Price2 -------- 56 65 Price3 -------- 234 3245 Any help is apprecieated, thanks if the above does not make sense to you maybe this will: "can you make 3 aliases of the same column and only display the rows inside each column where pricelist = 1 for the 1st alias... where price = 2 for the 2nd alias...where pricelist = 3 for the 3rd alias"
View Replies !
Using One Alias For Mutiple Columns In A SELECT Statement
Hi all,Is this at all possible? In the following query I have mutiple columns in my SELECT statement that each have their own alias. Is it possible that I can use just one Alias for all these columns (such as Address), and if so how is it done?SELECT RTRIM(ISNULL(ta.house_no_flat, '')) as [Target - Flat No.], LOWER(RTRIM(ISNULL(ta.building, ''))) as [Target - Building], LOWER(RTRIM(ISNULL(ta.road_street, ''))) as [Target - Street], LOWER(RTRIM(ISNULL(ta.district, ''))) as [Target - District], LOWER(RTRIM(ISNULL(ta.town, ''))) as [Target - Town], LOWER(RTRIM(ISNULL(ta.county, ''))) as [Target - County], RTRIM(ISNULL(ta.postcode, '')) as [Target - PostCode]ThanksTryst
View Replies !
Using One Alias For Mutiple Columns In A SELECT Statement
Hi all, Is this at all possible? In the following query I have mutiple columns in my SELECT statement that each have their own alias. Is it possible that I can use just one Alias for all these columns (such as Address), and if so how is it done? Code: SELECTRTRIM(ISNULL(ta.house_no_flat, '')) as [Target - Flat No.], LOWER(RTRIM(ISNULL(ta.building, ''))) as [Target - Building], LOWER(RTRIM(ISNULL(ta.road_street, ''))) as [Target - Street], LOWER(RTRIM(ISNULL(ta.district, ''))) as [Target - District], LOWER(RTRIM(ISNULL(ta.town, ''))) as [Target - Town], LOWER(RTRIM(ISNULL(ta.county, ''))) as [Target - County], RTRIM(ISNULL(ta.postcode, '')) as [Target - PostCode] Thanks Tryst
View Replies !
Dataset Query With Alias Column And Allow Searches
I have a form that loads a dataset. This dataset is composed from SQL statements using alias and unions. Basically it takes uses data from 3 tables. This dataset also has a alias column called ClientName that consists of either people's name or business name.In addition, the form also consist of a search field that allows user to enter the 'ClientName' to be searched (i.e. to search the alias column). So, my question is how can the alias column be searched (user can also enter % in the search field)Function QueryByService(ByVal searchClientNameText As String) As System.Data.DataSet If InStr(Trim(searchClientNameText), "%")>0 Then searchStatement = "WHERE ClientName LIKE '" & searchClientNameText & "'"Else searchStatement = "WHERE ClientName = @searchClientNameText"End If Dim queryString As String = "SELECT RTrim([People].[Given_Name])"& _"+ ' ' + RTrim([People].[Family_Name]) AS ClientName, [Event].[NumEvents],"& _"[Event].[Event_Ref]"& _"FROM [Event] INNER JOIN [People] ON [Event].[APP_Person_ID] = [People].[APP_Person_ID]"& _searchStatement + " "& _"UNION SELECT [Bus].[Organisation_Name],"& _"[Event].[NumEvents], [Event].[Event_Ref]"& _"FROM [Bus] INNER JOIN [Event] ON [Bus].[APP_Organisation_ID] = [Event].[APP_Organisation_ID] "& _searchStatement ..........End Function
View Replies !
The Column Prefix 'h' Does Not Match With A Table Name Or Alias Name Used In The Que
Hi Guys, I have a program that connects to SQLServer 2000 through ADO connection. the program executes the following query: SELECT ax.AccNo, (SELECT Accounts.ProductCode FROM Accounts WHERE h.ID=Accounts.ID) As Product FROM dbo.History h LEFT OUTER JOIN dbo.AccXRef ax ON h.ID= ax.ID LEFT OUTER JOIN dbo.States ON h.[HistoryItemsub-Type] = dbo.States.Type LEFT OUTER JOIN dbo.CustXRef cx ON h.CustomerNo = cx.CustomerNo WHERE HistoryItemDate <= getdate() ORDER BY HistoryItemDate ASC This query works in th program and in Query Analyer on my machine. However, On a different Machine (and different SQLServer) the query works in Query Analyser but does not work in the program, the following exception is thrown: The column prefix 'h' does not match with a table name or alias name used in the query Any help is greatly appreciated.. thanx in-advance, TNT:)
View Replies !
The Column Prefix 'MS1' Does Not Match With A Table Name Or Alias Name Used In The...
I have an Access database, that is in connection with sql server. On my computer with access2007 i have no problems with viewing tables and stuff. But on other computers with access2003 it gives an error when i use this query: INSERT INTO [tbl_sap-staffel] ( ItemCode, CardCode, [Amount-0], [Price-0], [Amount-1], [Price-1], [Amount-2], [Price-2] ) SELECT [qry_sap-spp-0].ItemCode, [qry_sap-spp-0].CardCode, [qry_sap-spp-0].Amount, [qry_sap-spp-0].Price, [qry_sap-spp-1].Amount, [qry_sap-spp-1].Price, [qry_sap-spp-2].Amount, [qry_sap-spp-2].Price FROM ([qry_sap-spp-0] LEFT JOIN [qry_sap-spp-1] ON ([qry_sap-spp-0].ItemCode = [qry_sap-spp-1].ItemCode) AND ([qry_sap-spp-0].CardCode = [qry_sap-spp-1].CardCode)) LEFT JOIN [qry_sap-spp-2] ON ([qry_sap-spp-1].ItemCode = [qry_sap-spp-2].ItemCode) AND ([qry_sap-spp-1].CardCode = [qry_sap-spp-2].CardCode); It says: ODBC call failed [Microsoft][ODBC SQL Server Driver][SQL Server] The column prefix 'MS1' does not match with a table name or alias name used in the query. The column prefix 'MS2' does not match with a table name or alias name used in the query. And it will give this error 6 times. I dont know what to do. Can anybody help me?
View Replies !
Get Column Alias From View AND Phisical Attribute
Hello Everyone, I am creating a Metadata management application for a business intelligence platform on SQL Server 2005. For this purpose, I've set out to consolidate all DB-object metadata (Databases, Tables, Columns, Views) into a single repository that business users can browse through. It has been fairly straightforward so far, but I've hit a wall in the views department. In fairly simple terms, I want to know which physical columns are selected in a view, with the twist of also knowing the columns' alias. This seems to be impossible as far as I can tell, it is easy enough to get both of these independently, but I can't figure out how to connect an alias to an actual column. (I prefer to use the metadata catalog views to the INFORMATION_SCHEMA as I need to know the object_id's) Aliases are easy enough to obtain: select object_id, column_id, name from sys.columns where object_id = object_id('SomeViewsName'); As are the 'physical' columns: SELECT t.object_id as TABLE_OID, c.column_id as COLUMN_OID, c.name FROM sys.views v JOIN sys.sql_dependencies d ON d.object_id = v.object_id JOIN .sys.objects t ON t.object_id = d.referenced_major_id JOIN sys.columns c ON c.object_id = d.referenced_major_id AND c.column_id = d.referenced_minor_id WHERE d.class < 2 AND v.name = 'SomeViewsName'; As I've said before, the problem is joining these two datasets. One of the problems associated with this is that the latter query also returns columns used in JOIN statements, even if they are not projected in the select part of the view definition. Ultimately I'd like to get this result: Alias used in View, physical table's object id, physical column's id Am I missing something? Thank you very much in advance for your help.
View Replies !
Fetch Metadata From A Column With An Alias In A View
Hi! I have created a view and one of the columns in the view has an alias assigned to it. I'm able to read the metadata from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE and also lookup from which table each column in the view orginated from except for the column that has an alias assigned to it. Is there any other way to lookup a column that has an alias assigned to it? Thanks alot! Adam
View Replies !
Query Builder - Alias Column Values
Hi, I am creating queries with a number of tables with some of the column names the same. The query builder generates alias's Expr1... Is there anyway to change this, or can a function be added to the alias column so i can generate more meaningful names automatically without having to change them one at a time. Thanks, Ali.
View Replies !
Get Column Alias From View AND Phisical Attribute
Hello Everyone, I am creating a Metadata management application for a business intelligence platform on SQL Server 2005. For this purpose, I've set out to consolidate all DB-object metadata (Databases, Tables, Columns, Views) into a single repository that business users can browse through. It has been fairly straightforward so far, but I've hit a wall in the views department. In fairly simple terms, I want to know which physical columns are selected in a view, with the twist of also knowing the columns' alias. This seems to be impossible as far as I can tell, it is easy enough to get both of these independently, but I can't figure out how to connect an alias to an actual column. (I prefer to use the metadata catalog views to the INFORMATION_SCHEMA as I need to know the object_id's) Aliases are easy enough to obtain: select object_id, column_id, name from sys.columns where object_id = object_id('SomeViewsName'); As are the 'physical' columns: SELECT t.object_id as TABLE_OID, c.column_id as COLUMN_OID, c.name FROM sys.views v JOIN sys.sql_dependencies d ON d.object_id = v.object_id JOIN .sys.objects t ON t.object_id = d.referenced_major_id JOIN sys.columns c ON c.object_id = d.referenced_major_id AND c.column_id = d.referenced_minor_id WHERE d.class < 2 AND v.name = 'SomeViewsName'; As I've said before, the problem is joining these two datasets. One of the problems associated with this is that the latter query also returns columns used in JOIN statements, even if they are not projected in the select part of the view definition. Ultimately I'd like to get this result: Alias used in View, physical table's object id, physical column's id Am I missing something? Thank you very much in advance for your help.
View Replies !
Column Alias Asthe Current Time Stamp
Hey All, I am new to programming in SQL developer and I was hoping one of you kind salmon of knowledge could help me I am running an SQL script every 15 minutes to pull data. I would like to insert the results into a column in a table. I have two issues: 1.How can I give the result column the current time stamp as an alias? 2.How can I add this column to the results table (I know its Alter table but do I put this into the insert sql?) I would appreciate any help possible Thanks
View Replies !
SQL Msg 107 Error... The Column Prefix Does Not Match With A Table Name Or Alias Name Used In The Query.
Can someone please answer a problem that I've run into. I know that it's probably something stupid. I keep getting this error:Server: Msg 107, Level 16, State 3, Line 1The column prefix 'vFirstTimeEntered' does not match with a table name or alias name used in the query.Here is my query:-----------------------------------------------------------------Update TimeSheetSectionSet TimesheetSection.SECSTARTDT = vFirstTimeEntered.schlstuidWhere timesheetsection.schlstuid = vFirstTimeEntered.schlstuid AND timesheetsection.sectionid = vFirstTimeEntered.sectionid AND Timesheetsection.secstartdt < '2005-08-01'------------------------------------------------------------------vFirstTimeEntered is a view that I created.Do I need a sub query? I know that if this was a select query I'd need to put vFirstTimeEntered in the FROM part but I don't know where it should go here.Thanks for any assistance.Scott
View Replies !
Joining On And Grouping By CASE Function Column Alias (URGENT)
I REALLY need to perform a JOIN and a GROUP BY on a CASE function column alias, but I'm receiving an "Invalid column name" error when attempting to run the query. Here's a snippet: SELECT NewColumn= CASE WHEN Table1.Name LIKE '%FOO%' THEN 'FOO TOO' END, Table2.SelectCol2 FROM Table1 JOIN Table2 ON NewColumn = Table2.ColumnName GROUP BY NewColumn, Table2.SelectCol2 ORDER BY Table2.SelectCol2 I really appreciate any help anyone can provide. Thanks, DC Ross
View Replies !
Correlated Subquery - Column Prefix 'OJ' Does Not Match With A Table Name Or Alias Name Used In The Query.
I have data in a table (@Outer) that I am matching to a lookup table (@Inner) which contains multiple "matches" where nulls can match any value. By sorting the inner table and grabbing the top record, I find the "best" match. I know the sort and the null matches work but I don't understand why the correlated sub query below doesn't understand that the OJ prefix refers to the outer table.DECLARE @Outer TABLE ( OuterID int IDENTITY (1, 1) NOT NULL, MethodID int NULL, CompID int NULL, FormID int NULL, InnerID int NULL ) INSERT @Outer VALUES (2, 2, 2, NULL) -- OuterID = 1 INSERT @Outer VALUES (3, 2, 1, NULL) -- OuterID = 2 DECLARE @Inner TABLE ( InnerID int IDENTITY (1, 1) NOT NULL, MethodID int NULL, CompID int NULL, FormID int NULL ) INSERT @Inner VALUES (2, null, null) -- InnerID 1 INSERT @Inner VALUES (2, null, 1) -- InnerID 2 INSERT @Inner VALUES (2, 2, null) -- InnerID 3 INSERT @Inner VALUES (3, null, null) -- InnerID 4 INSERT @Inner VALUES (3, 2, null) -- InnerID 5 INSERT @Inner VALUES (4, 2, 1) -- InnerID 6 -- UPDATE Outer Table with best match from Inner table UPDATE @Outer SET InnerID = IJ.InnerID FROM @Outer OJ INNER JOIN ( SELECT TOP 1 I.* FROM @Inner I WHERE IsNull(I.MethodID, OJ.MethodID) = OJ.MethodID AND IsNull(I.CompID, OJ.CompID) = OJ.CompID AND IsNull(I.FormID, OJ.FormID) = OJ.FormID ORDER BY I.MethodID DESC, I.CompID DESC, I.FormID DESC ) IJ ON OJ.MethodID = IsNull(IJ.MethodID, OJ.MethodID) AND OJ.CompID = IsNull(IJ.CompID, OJ.CompID) AND OJ.FormID = IsNull(IJ.FormID, OJ.FormID) SELECT * FROM @Outer The result should be OuterID 1 matched to Inner ID 3 and OuterID 2 matched to Inner ID 5. Can anyone help me? Thanks in advance.
View Replies !
Custom Column Alias (Reporting Services 2005) When Designing Reports From MDX Queries
Hi All, In T-SQL, it is easy to to provide a column alias example "CustomerName" AS Name, "CustomerPhone" AS Phone, etc. When we are developing SSRS 2005 reports using MDX , when the columns are a result of cross joins on ROWS , I don't know a way to provide a column alias within the MDX query. If anybody knows then please share. But I have found a easy solution. 1) Switch to the 'Layout' tab of the report designer 2) Click on View->Datasets (or press Ctrl+Alt+D) to bring the datasets. 3) Expand the datasets, highlight the dataset where you want to change the column name. 4)Right Click the column name you want to 'rename', then click on 'Edit' 5)Under 'Edit Field' change the 'Name' to the name you want to.(Example : your previous column name was 'CustomerPhone' , change it to 'Phone' 6)Once you have changed the column name, the fields with (=Fields!CustomerPhone.value) has to be changed to (=Fields!Phone.value).So Drag and Drop the fields again 7) Run the report..Enjoy.... You may need to change the column name because of certain business requirements. I had a requirement where an XML parser requires the field names to follow certain naming conventions. Another way to chnage the 'column' name is to change the 'Name' property of the column. Thanks Bidyut
View Replies !
Invalid Column Name
Hi the following SP that causes an error. CREATE PROCEDURE GetInfo ( @MinPriceint=0, @MaxPriceint=9999999999, @TypeHomenvarchar(50)=NULL, @Locationnvarchar(100)=NULL ) AS Declare @strSql nvarchar(255) Set @strSql="Select * from table WHERE " Set @strSql=@strSql + 'Price BETWEEN ' + CONVERT(nvarchar(20),@MinPrice) + ' and ' + CONVERT(nvarchar(20),@MaxPrice ) If @TypeHome != "No Preference" Set @strSql=@strSql + ' and Type = ''' + @TypeHome+ '''' If @Location != "No Preference" Set @strSql=@strSql + ' and City = ''' + @Location+ '''' Set @strSql=@strSql + ' and IDX = ''Y'' ORDER BY Price' Exec(@strSql) GO The Error I get is: "Error 207: Invalide Column Name 'Select * from table WHERE' Invalid Column Name 'No Preference' Invalid Column Name 'No Preference' I have checked the table and the columns do exist, spelled correctly and caps are all the same. Also, this same SP in another table works just fine. What is causing this error? Thanks in advance!
View Replies !
Invalid Column Name
I get a Invalid Column Name ' '. with this procedure. Can anyone see what migh be wrong? Thanks, SELECT A.CompanyName,C.FirstName,C.LastName,C.Client_ID, CASE WHEN A.[CompanyName] IS NULL OR A.[CompanyName] = '' THEN C.[FirstName] +" "+ C.[LastName] ELSE A.[CompanyName] END AS DRName, C.Client_ID FROM tblClients C INNER JOIN tblClientAddresses A ON C.Client_ID = A.Client_ID WHERE (C.Client_ID = 15057) AND (A.MailTo=1) AND Convert(varchar(5), GETDATE(), 10) BETWEEN Convert(varchar(5), A.Startdate, 10) AND Convert(varchar(5), A.Enddate, 10) OR (A.Startdate Is Null) AND (A.EndDate Is Null) GO
View Replies !
Invalid Column Name
Hi I have a dynamic select statement which is showed below. declare @query varchar(100) set @query = 'select * from undergraduate where Gender =' + @Gender exec (@query) // When I execute the @query, I get an error message like "Invalid Column Name Male". I think I need to put a single quotation around the dynamic variable, so that I have select * from undergraduate where Gender ='Male'. But I am not sure how to do that. Thank you for your help!!
View Replies !
Invalid Column Name 'x'
Can anyone tell me why I get the above message using the following stored procedure and passing in a value of 120: CREATE Procedure qryAnalysisCountMain (@WizardGroup1Question int) As EXEC("SELECT QuestionDescription FROM Questions WHERE QuestionCode = " + @WizardGroup1Question) 120 just happens to be the asci value of 'x' and whatever number I pass in gets converted into it's character equivalent and the sp tells me it can't find that column name. QuestionCode is an int field so there is no problem there The procedure works OK with: SELECT QuestionDescription FROM Questions WHERE QuestionCode = @WizardGroup1Question However I need the SQL in an EXEC as the sp will eventually be dynamic so that i can pass in the name of the table to select from. Thanks Martin
View Replies !
Invalid Column Name
Hi, Can I write parameter name like shown below? Code Snippet SELECT 'N' AS LiquidatingFlag, Report, RptSection, Portfolio, RepExcRsn, Units, FROM Exc_SummaryData_Custom WHERE (Report IN (@Report)) AND (Portfolio IN (@Portfolio)) AND ( LiquidatingFlag IN(@LiquidatingFlag)) UNION ALL SELECT 'R' AS LiquidatingFlag, Report, RptSection, Portfolio, RepExcRsn, Units, FROM Exc_SummaryData_Custom_LIQ WHERE ( Report IN (@Report)) AND (Portfolio IN (@Portfolio)) AND ( LiquidatingFlag IN (@LiquidatingFlag)) I get a error message saying invalid column name LiquidatingFalg. (Actually there is no clumn in the original table)Can any one help to work this correctly?
View Replies !
Invalid Column Name?
Is there not a way to perform a calculation on a column comprised from a Case Function? This is my query: SELECT 'ComparativeValue' = CASE WHEN Id = 1 THEN Index WHEN Id = 2 THEN Peers WHEN Id = 3 THEN PrevYear END, Variance = (Base - ComparativeValue)/ComparativeValue FROM Table I get this error when trying to execute the query: Invalid column name 'ComparativeValue'.
View Replies !
Invalid Column Name
Below is the T-SQL SELECT ci.name, ci.address, CASE ISNULL(cci.geography,'') WHEN 'P' THEN 'port' WHEN 'A' THEN 'appt' WHEN 'X' THEN 'xatt' ELSE '' END AS Link, ci.InsuranceType FROM dbo.Insurance ci INNER JOIN dbo.Contract cci ON ci.InsuranceId = cci.InsuranceId AND cci.ContractId = 1266 ORDER BY ci.Link, ci.InsuranceType =========================== My work environment is all in SQL SERVER 2005. I have a problem with above T-SQL. There is an error while I run above code in Develoment Server.The error disappears when I put 'ci.Link' as 'Link' in OrderBy clause. My work environment has TEST, PRE-PRODUCTION and PRODUCTION. In all other environments the code runs fine with ci.Link but only in DEVELOPMENT the error persists. It has an error as 'Link is invalid column name'.
View Replies !
Invalid Column Name
I need to identify where this column could be, I have checked in the syscolumns but did not find it as a result I am now having to manually check each view and sp that could use the column so I can transfer the database to my new SQL 2005 machine. Is there an easier way to identify this coloumn by some sort of search??
View Replies !
Invalid Column
Hello All, I m facing problem in one query. What I did is SELECT PRODUCT_ID, PRODUCT_END_DATE, CASE WHEN PRODUCT_ID = 1 THEN DATEADD(YY,-5,PRODUCT_END_DATE) WHEN PRODUCT_ID = 2 THEN DATEADD(YY,-10,PRODUCT_END_DATE) WHEN PRODUCT_ID = 3 THEN DATEADD(YY,-15,PRODUCT_END_DATE) END AS MODIFIED_END_DATE FROM PRODUCTS WHERE MODIFIED_END_DATE BETWEEN '2008-04-01' AND '2008-04-30' when I execute this query returns an error as Invalid column name MODIFIED_END_DATE So how can I write this query? any idea. Thanks in advance. --kneel
View Replies !
Invalid Column Name
Hi I'm new to this forum and I seem to be having a basic problem. I have moved from using MS Access to SQL Server and I seem to be having problem with the SQL below. SELECT Table_A.*, (Statement_A) AS Value_A , (Value_A + 4) AS Value_B FROM Table_A I keep on getting an error stating invalid column name, I know that statement A is fine because when I move the calculation into Value_B it works. Can anyone tell me what I am doing wrong?
View Replies !
Invalid Column Name
I am building a query and thought I had completed it but I get 'Invalid Column Name "A1" when I run it? SELECT Groups.GroupID, Sum(Stages_On_Route.Distance) AS Miles_Covered, Groups.Group_Name FROM Groups INNER JOIN ((Route INNER JOIN Departure ON (Route.GroupID=Departure.GroupID) AND (Route.RouteID=Departure.RouteID)) INNER JOIN Stages_On_Route ON Route.RouteID=Stages_On_Route.RouteID) ON Groups.GroupID=Departure.GroupID GROUP BY Groups.GroupID, Groups.Group_Name HAVING (((Groups.GroupID)="A1"));
View Replies !
Invalid Column Name But Right
I have my column names right but its telling me they are invalid. It must be something to do with how I have my subquery formatted but I don't see it. I was wondering if anyone else can see it? It tells me payer_id is not right and I know its coming from the bolded section. I just added that line to do some additional grouping. I know that the query above aliased as D was working before I put the bolded line in. Am I setting this up wrong? select distinct c.description,tmp.person_id,tmp.person_nbr,tmp.first_name, tmp.last_name,tmp.date_of_birth,d.payer_name,b.create_timestamp from PersonMIA tmp join person a on a.person_id = tmp.person_id join patient_encounter b on a.person_id = b.person_id join provider_mstr c on b.rendering_provider_id = c.provider_id cross apply(select top 1 payer_name from person_payer where person_id = tmp.person_id order by payer_id) d join payer_mstr e on d.payer_id = e.payer_id join mstr_lists f on e.financial_class = f.mstr_list_item_id where c.description = 'Leon MD, Enrique' group by c.description,tmp.person_id,tmp.person_nbr,tmp.first_name,tmp.last_name, tmp.date_of_birth,d.payer_name,b.create_timestamp )tmp2 where year(create_timestamp) IN (2005,2006) group by person_nbr,payer_name,first_name,last_name,description,create_timestamp Thanks in Advance! Sherri
View Replies !
Invalid Column Name 'Ploeg'.
When i try to execute i receive following error: Msg 207, Level 16, State 1, Procedure WedstrijdDeelnemersSelectAllMPNietGoedgekeurd, Line 85 Invalid column name 'Ploeg'. I dont really see whats wrong with the select... it works fine in the 2 first parts of the querryALTER PROCEDURE [dbo].[WedstrijdDeelnemersSelectAllMPNietGoedgekeurd] -- Add the parameters for the stored procedure here @WedstrijdID int AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; ... UNION SELECT dbo.fncGetPersoonNaam(L.PersoonID,0) as Persoon, 'Ploeg: ' + WDPI.Ploeg as TypeInschrijving, WDPIL.LidClubID, WT.Omschrijving as WedstrijdType, C.Omschrijving as Categorie, WDC.WedstrijdDetailID, WDC.ID as WedstrijdDetailCategorieID, WDPI.ID as TypeInschrijvingID FROM Wedstrijd W INNER JOIN WedstrijdDetail WD ON W.ID = WD.WedstrijdID INNER JOIN WedstrijdType WT ON WD.WedstrijdTypeID = WT.ID INNER JOIN WedstrijdDetailCategorie WDC ON WD.ID = WDC.WedstrijdDetailID INNER JOIN Categorie C ON WDC.CategorieID = C.ID INNER JOIN WedstrijdDetailPloegInschrijving WDPI ON WDC.ID = WDPI.WedstrijdDetailCategorieID INNER JOIN WedstrijdDetailPloegInschrijvingLid WDPIL ON WDPIL.WedstrijdDetailPloegInschrijvingID = WDPI.ID ...END
View Replies !
Invalid Column Name From C# Sql Query
Hi I have the following problem. I am trying to get some data from a database which matches the name in a session from a previous page:e.g. SqlCommand menubar = new SqlCommand("Select pernme from Person where pernme = " + (string)Session["tbname"], sqlConn); SqlDataAdapter dataAdapter5 = new SqlDataAdapter(); dataAdapter5.SelectCommand = menubar; DataSet dataSet5 = new DataSet(); dataAdapter5.Fill(dataSet5); DataTable selcartest4 = dataSet5.Tables["table"]; if (selcartest4.Rows.Count != 0)The session is called tbname and in that session is a users name however insetad of doing the nornal thing and retrieving the data in the sql database table matching that name it comes up with the following error message:System.Data.SqlClient.SqlException: Invalid column name 'jamie'this is weird as the 'jamie' is the name in the session from the previous page and in fact not a column name at all the column name is pernme I am totally stuck any help would eb great thanksJ
View Replies !
Invalid Column Exception
Hi, I have the following query "SELECT Test_Question.Question_ID, Test_Question.Grade_Number as GNum, Test_Question.Question_Number as QNum, Question.Question_Text as QText , Answer.Answer_Number as AnsNum, Answer.Answer_Text as AnsTxt, Answer.ID AS Ans_ID FROM Test_Question, Question, Answer WHERE Test_Question.Active=1 AND Test_Question.Question_ID = Question.ID AND Test_Question.Deleted=0 and Test_Question.Test_Detail_ID ="+ currPTestId +" AND Question.ID = Answer.Question_ID GROUP BY Test_Question.Question_ID ORDER BY Test_Question.Question_Number, Test_Question.Question_ID, Answer.Answer_Number"; But I get an exception column Test_Question.Grade_Number is invalid in the select list because it is not contained in either an aggregate function or the group by clause. Could some one point out what is the problem in the above query. thanks in advance shail
View Replies !
SqlException: Invalid Column Name
Hello, I have a problem with my Update sql server command. The error message is strange : System.Data.SqlClient.SqlException: Invalid column name 'CMD_DATE_ORDER'. Invalid column name 'CMD_REF_CLIENT'. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ASP.addorder_aspx.MasterGrid_Update(Object Sender, DataGridCommandEventArgs E) in C:Inetpubwwwrootproject1addorder.aspx:line 157 On line 157 I have : UpdateCommand.ExecuteNonQuery() The Update code : Sub MasterGrid_Update(Sender As Object, E As DataGridCommandEventArgs) ' update the database with the new values ' get the edit text boxes Dim dateCom As String = CType(e.Item.FindControl("dateCom"), TextBox).Text Dim NumBon As String = CType(e.Item.FindControl("NumBon"), TextBox).Text Dim NomDest As String = CType(e.Item.FindControl("NomDest"), TextBox).Text Dim NovoieDest As String = CType(e.Item.FindControl("NovoieDest"), TextBox).Text Dim nomvoieDest As String = CType(e.Item.FindControl("nomvoieDest"), TextBox).Text Dim cpDest As String = CType(e.Item.FindControl("cpDest"), TextBox).Text Dim villeDest As String = CType(e.Item.FindControl("villeDest"), TextBox).Text Dim paysDest As String = CType(e.Item.FindControl("paysDest"), TextBox).Text Dim telDest As String = CType(e.Item.FindControl("telDest"), TextBox).Text Dim dateExp As String = CType(e.Item.FindControl("dateExp"), TextBox).Text Dim myConnection As New SqlConnection(strConnect) Dim UpdateCommand As SqlCommand = new SqlCommand() UpdateCommand.Connection = myConnection ' Add to CLIID_LGN the selected value in the DropDownList Dim cliid As String cliid = Trim(DDL.SelectedItem.Value) If AddingNew = True Then UpdateCommand.CommandText = "INSERT INTO Commandes (CMD_DATE_ORDER, CMD_NUM_BON_ORDER, CMD_NOM_DEST, CMD_NOVOIE_DEST, CMD_NOMVOIE_DEST, CMD_CP_DEST, CMD_VILLE_DEST, CMD_PAYS_DEST, CMD_TEL_DEST, CMD_DATE_EXPED, CMD_REF_CLIENT) VALUES ('" & dateCom & "','" & NumBon & "','" & NomDest & "','" & NovoieDest & "','" & nomvoieDest & "','" & cpDest & "','" & villeDest & "','" & paysDest & "','" & telDest & "', '" & dateExp & "', '" & cliid & "')" Else UpdateCommand.CommandText = "UPDATE Client SET CMD_DATE_ORDER=@dateCom, CMD_NUM_BON_ORDER = @NumBon, CMD_NOM_DEST = @NomDest, CMD_NOVOIE_DEST = @NovoieDest, CMD_NOMVOIE_DEST = @NomvoieDest, CMD_CP_DEST = @cpDest, CMD_VILLE_DEST = @villeDest, CMD_PAYS_DEST = @paysDest, CMD_TEL_DEST = @telDest, CMD_DATE_EXPED = @dateExp WHERE CMD_REF_CLIENT = '" & cliid & "'" End If UpdateCommand.Parameters.Add("@dateCom", SqldbType.SmallDateTime, 4).Value = Trim(dateCom) UpdateCommand.Parameters.Add("@NumBon", SqldbType.NVarChar, 10).Value = Trim(NumBon) UpdateCommand.Parameters.Add("@NomDest", SqldbType.NVarChar, 50).Value = Trim(NomDest) UpdateCommand.Parameters.Add("@NovoieDest", SqldbType.NVarChar, 5).Value = Trim(NovoieDest) UpdateCommand.Parameters.Add("@nomvoieDest", SqldbType.NVarChar, 80).Value = Trim(nomvoieDest) UpdateCommand.Parameters.Add("@cpDest", SqldbType.NVarChar, 5).Value = Trim(cpDest) UpdateCommand.Parameters.Add("@villeDest", SqldbType.NVarChar, 35).Value = Trim(villeDest) UpdateCommand.Parameters.Add("@paysDest", SqldbType.NVarChar, 35).Value = Trim(paysDest) UpdateCommand.Parameters.Add("@telDest", SqldbType.NVarChar, 14).Value = Trim(telDest) UpdateCommand.Parameters.Add("@dateExp", SqldbType.SmallDateTime, 4).Value = Trim(dateExp) ' execute the command Try myConnection.Open() UpdateCommand.ExecuteNonQuery() Catch ex as Exception Message.Text = ex.ToString() Finally myConnection.Close() End Try ' Resort the grid for new records If AddingNew = True Then MasterGrid.CurrentPageIndex = 0 AddingNew = false End If ' rebind the grid MasterGrid.EditItemIndex = -1 BindMasterGrid() End Sub I have send a response.write instruction : the values are all good. In the sql server database, the syntax of this 2 fields CMD_DATE_ORDER and CMD_REF_CLIENT are good. Can you help me for this problem ? Thanks.
View Replies !
|