Specifying Column Name As A Parameter in SELECT statement? - sql

I need to do something like this, but it always fails with 'Error converting data type varchar to int':
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
SET #intParam = SELECT #ColName FROM myTable
How do I accomplish something like this? I can see the problem is that the SELECT statement simply returns the column name as a string, but I am not sure how to fix that. I am using SQL Server 2008R2.

You need to use dynamic sql:
build your dynamic SQL query (take a look at #SQL variable in sample below)
use output parameter to get value back from dynamic sql (take a look at #intParam and #intParam_out in sample below)
execute dynamic sql using sp_executesql
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT #intParam_out = ' + #ColName + ' FROM myTable'
exec sp_executesql #SQL, N'#intParam_out int OUTPUT', #intParam_out = #intParam OUTPUT

Use Cast:
SET #intParam = SELECT cast(#ColName as int) FROM myTable

Related

Issues with equal sign when assigning statement to # variable for EXEC sp_executesql

Hello: I am trying to encapsulate the following Insert and select statement into a variable for SQL to run.
The issue occurs when the equals sign is included for evaluation (or right around there)
The CustomPollerAssignmentID Column had to be cast since it natively a PK and a uniqueidentifier (see image)
What must be done to have the statement evaluate properly when passes to the sp_executesql?
I receive a syntax error as illustrated below
declare
#date datetime,
#query nvarchar(Max)
set #date = getdate()-4
set #query = --'Insert into [SolarWindsOrion].[dbo].[BWC_VPN_Hourly_Long_Store]
'SELECT * FROM [SolarWindsOrion].[dbo].[CustomPollerStatistics_Hourly]
where Cast(CustomPollerAssignmentID as nvarchar(max)) = 63FEB60-4516-4C1A-9A11-DB30ACA44301'
EXEC sp_executesql #query
UPDATE-->
I tried adding the single quotes.
While the statement does execute.. no results are returned. See Image below
you need to put it in quote like this '63FEB60-4516-4C1A-9A11-DB30ACA44301' , so your adhoc query would look like this :
declare
#date datetime,
#query nvarchar(Max)
set #date = getdate()-4
set #query = --'Insert into [SolarWindsOrion].[dbo].[BWC_VPN_Hourly_Long_Store]
'SELECT * FROM [SolarWindsOrion].[dbo].[CustomPollerStatistics_Hourly]
where Cast(CustomPollerAssignmentID as nvarchar(max)) = ''63FEB60-4516-4C1A-9A11-DB30ACA44301'''
EXEC sp_executesql #query

Is it possible to set a part of a select statement in a variable

I have a query of which the select-part is really long. I'd like to split this in several pieces, especially because some parts are in there twice or even more often.
What I'd like is something like the following:
Declare #SQLPart as varchar(1000)
Set #SQLPart = 'Field1,
case ... as Field2,'
Select ..., #SQLPart, ... From .....
Unfortunately this results error messages. I tried something like EXEC(#SQLPart) as well but of course this also didn't work. How would I solve this?
Yes, dynamic sql and sp_executesql:
CREATE TABLE ##Temp (Field1 int, Field2 int)
Declare #SQLPart nvarchar(1000)
Set #SQLPart = N'Field1, Field2 '
DECLARE #SQL nvarchar(1000) = N'SELECT ' + #SQLPart + 'FROM ##Temp'
PRINT #SQL
EXEC sp_executesql #SQL
DROP TABLE ##Temp
Your SQL code must be nvarchar type.
Alse sp_executesql is better than EXECUTE function, when you have many similar queries, sp_executesql caches executaion plans, and it can be better in perfomance.
You can use dynamic sql here,and use a EXECUTE keyword to execute this dynamic query
Declare #SQLPart as varchar(1000)
Set #SQLPart = 'Field1,
case ... as Field2,'
EXECUTE ('SELECT ....,'+#SQLPart+',... FROM ...')
SQL Server does not support Macro-Substitution, so you would have to use Dynamic SQL.
Declare #SQL varchar(max) ='Select ... ' + #SQLPart + '... from ...'
Exec(#SQL)

CAST and CONVERT in T-SQL

Is it posible to CAST or CONVERT with string data type (method that takes data type parametar as string), something like:
CAST('11' AS 'int')
but not
CAST('11' AS int)
No. There are many places in T-SQL where it wants, specifically, a name given to it - not a string, nor a variable containing a name.
If you want to use dynamic sql, this should get you started:
DECLARE #datatype varchar(20)
DECLARE #sql varchar(4000)
SELECT #datatype = 'int'
SELECT #sql = 'PRINT CAST(''11'' AS '+#datatype+')'
exec (#sql)
Depending on what you exactly want/need you should read The Curse and Blessings of Dynamic SQL, especially the parts about sp_executesql
You would have to use dynamic sql to achieve that:
DECLARE #type VARCHAR(10) = 'int'
DECLARE #value VARCHAR(10) = '11'
DECLARE #sql VARCHAR(MAX)
SET #sql = 'SELECT CAST(' + #value + ' AS ' + #type + ')'
EXEC (#sql)
SQLFiddle DEMO with INT
// with datetime

How to set a variable to the result of a sql query with a variable as a table name in SQL 2005

I'm currently having trouble writing a stored procedure and setting the value of a variable of type int to the results of a select statement with a variable as the tablename. I've looked at old threads and tried multiple methods, but no luck. If I'm not getting an error regarding the tablename, I end up getting an error with a variable conversion issue. I've been working on this for too long and any help would be appreciated. Below is a portion of my code. Thanks
DECLARE #BATCHNUMBER VARCHAR --value set in earlier code
DECLARE #ETABLE VARCHAR(50); --the table name
DECLARE #FIRSTDOCID INT;
SET #ETABLE = 'tablename_' + #BATCHNUMBER; --CREATE FIRST TABLE NAME
SELECT #FIRSTDOCID = MIN(D0CID) FROM #ETABLE
The error I get is: Must declare the table variable "#ETABLE"
You are trying to select from a VARCHAR, not a table. The only way to make this work is by using Dynamic SQL.
DECLARE #SQL NVARCHAR(250);
SET #SQL = 'SELECT #OUTPUT = MIN(D0CID) FROM ' + QuoteName(#ETABLE);
EXEC sp_executeSql #SQL, N'#output INT OUTPUT', #FIRSTDOCID OUTPUT;
SELECT #FIRSTDOCID;
However, I would not suggest using Dynamic SQL as this often leads to SQL injection.
You'll probably have to do something like use exec if you're dynamically building the query:
SET #QUERY = "SELECT" + ...etc.
exec(#QUERY)
Since ETABLE is a varchar, and not, as expected, a 'table variable'.

Using variable inside dynamic SQL

I have the below SQL..What I am trying to do is use the Parameter defined at the stored procedure level inside dynamic SQL:
CREATE PROCEDURE [dbo].[Test]
(#DealID NVARCHAR(500),
#OUTPUT NVARCHAR(MAX) OUTPUT,
#FeeType CHAR(1)
) -- I want to use this parameter inside dynamic SQL query
AS
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(MAX)
BEGIN
SET #exec_str = N'DECLARE #ParmDefinition NVARCHAR(500)
SELECT * FROM #FeeType' --This is where I want to use the variable
DECLARE #ParamDefinition nvarchar(max)
SET #ParamDefinition = N'#OUTPUT NVARCHAR(MAX) OUTPUT'
EXEC sp_executesql #exec_str, #ParamDefinition
Can someone please tell me how to do it?
Thanks
In SQL Server Identifiers can't be parameterized.
Since you are using dynamic SQL anyway, you can do something like this:
SET #exec_str= N'Select * from '+ #FeeType
EXEC(#exec_str)
However, this is vulnerable to SQL injection attacks. To reduce the risk to minimum you should check first that such a table name exists, and I would also use quotename just to be on the safe side:
IF EXISTS
(
SELECT 1
FROM Information_Schema.Tables
WHERE TABLE_NAME = #FeeType
)
BEGIN
SET #exec_str= N'Select * from '+ QUOTENAME(#FeeType)
EXEC(#exec_str)
END