Solved

t-sql query

Posted on 2014-01-23
1
262 Views
Last Modified: 2014-01-23
Hi experts,

I'm using sql server 2008 R2.

I'm using the Employees table from the Northwind database

So I have 2 queries.

Query 1 is a working example.
Query 2 is the one that i'm having trouble with and need help with.



Query 1

This is the code for it:

-- Query 1
DECLARE @FromDate char(30), @ToDate char(30)
SET @FromDate = '02/01/1955'
SET @ToDate = '09/30/1955'
  
SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[BirthDate]
FROM [Northwind].[dbo].[Employees] e
WHERE
e.[BirthDate] Between RTrim(@FromDate) And RTrim(@ToDate) 

Open in new window


When I run this query I get this:

query 1 result set
Query 2

In this query my parameter called @WhatDay holds the name of the Birthdate column of the Employees table.

This is the code I have:

-- Query 2 
DECLARE @FromDate char(30), @ToDate char(30), @WhatDay char(50)

SET @FromDate = '02/01/1955'
SET @ToDate = '09/30/1955'
SET @WhatDay = 'BirthDate'
  
SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[BirthDate]
FROM [Northwind].[dbo].[Employees] e
WHERE
e.RTrim(@WhatDay) Between RTrim(@FromDate) And RTrim(@ToDate)     

Open in new window



In Sql Server management studio this is a screen shot of the error I'm getting:

my error message

How do I fix query 2?
0
Comment
Question by:maqskywalker
1 Comment
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 39805184
You can't use a variable to contain a column name in SQL Server.

If you want the column name to vary, you have to build a string and then execute it dynamically, i.e., you must use dynamic SQL.
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question