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
Related
I search about the error, but I only find different answers that didn't work for me.
I have this query, in SQL Server:
DECLARE #column_name varchar (25),
#data_column int,
#table_name varchar (25)
DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #column_name = 'Excellent'
SET #table_name = 'CSAT'
SET #data_column = 10
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+') VALUES('+#data_column+')'
EXEC (#mySql)
When I execute it, it shows me this error:
Conversion failed when converting the varchar value 'INSERT INTO CSAT(Excellent) VALUES(' to data type int.
All the columns are Int and allow nulls.
I have to make a conversion or something? I appreciate your help!
#data_column is an int, so you need to convert it to varchar because you are building a string.
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+')
VALUES('+ Convert(Varchar(10), #data_column)+')'
When sql server encounters an expression that mixes strings and int, it attempts to convert the string to an int (instead of the the other way around). This is documented here: SQL Server Data Type Precedence
add some space like this
SET #mySql = 'INSERT INTO '+#table_name+' ('+convert(varchar(50),#column_name)+') VALUES('+#data_column+')'
The sql is trying to make a sum of your string on line:
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+') VALUES('+#data_column+')'
Change the #data_column parameter from int to varchar or use a CONCAT function to create your SQL command:
SET #mySql = CONCAT('INSERT INTO ',#table_name,' (',#column_name,') VALUES(',#data_column,')')
You should use Parametrised Query to do this, Also use appropriate datatype for object names...
something like this....
SET NOCOUNT ON;
DECLARE #column_name SYSNAME
,#data_column INT
,#table_name SYSNAME
,#mySql NVARCHAR(MAX);
SET #column_name = 'Excellent'
SET #table_name = 'CSAT'
SET #data_column = 10
SET #mySql = N' INSERT INTO '+ QUOTENAME(#table_name)
+ N' ('+ QUOTENAME(#column_name) +') '
+ N' VALUES( #data_column )'
Exec sp_executesql #mySql
,N'#data_column INT'
,#data_column
I'm trying to pass in #accountType, a char value to a stored procedure that uses dynamic SQL. It is declared as char(4) in the procedure. The current error is Incorrect syntax near 'D' if I try to change it I get invalid column: D.
I cannot figure out how dynamic SQL wants me to indicate that the variable is a char. I've tried it many ways, here is the most recent:
set #q = 'Update ' + #statementTable +
' SET Account = '+ #padding + #accountNumber +
' WHERE ClosingDate BETWEEN CAST('''+CONVERT(VARCHAR(20),#proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(20),#proc_dateEnd)+''' AS DATE)' +
' AND AccountType =' + ''''+ #accountType +''''
The value is coming from my C# code exactly like this: D
No single quotes or anything around the letter. Any ideas? I'm more than a bit stuck with this.
Something like this, you need to have the parameters actually within the string statement, then when you execute sp_executesql, you then pass what each of those parameters are.
DECLARE #q VARCHAR(MAX)
DECLARE #statementTable VARCHAR(50)
DECLARE #padding VARCHAR(50)
DECLARE #accountNumber CHAR(4)
DECLARE #proc_dateStart VARCHAR(50)
DECLARE #proc_dateEnd VARCHAR(50)
DECLARE #accountType VARCHAR(50)
SET #q = 'Update #statementTable
SET Account = ''#accountNumber''
WHERE ClosingDate BETWEEN CAST(''+CONVERT(VARCHAR(20),#proc_dateStart)+'' AS DATE) AND CAST(''+CONVERT(VARCHAR(20),#proc_dateEnd)+'' AS DATE)
AND AccountType = ''#accountType'''
EXEC sys.sp_executesql #sql, N'#statementTable VARCHAR(50),#accountNumber CHAR(4),#proc_dateStart VARCHAR(50), #proc_dateEnd VARCHAR(50),#accountType VARCHAR(50)',
#statementTable,#accountNumber,#proc_dateStart,#proc_dateEnd,#accountType;
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
I know this is not possible, but is there something that would work? Basically I want the where statement to be dynamic, allowing me to pass it any string, which it will be able to search upon.
Declare #search varchar(80)
set #search = 'RegionID'
Select * from TBL_TripDetails
Where #search = '1'
Thanks for your answers. After reading a few documents, I have decided to use multiple select statements instead of using dynamic sql. thanks!
declare #sql nvarchar(max);
set #sql = N'select * from table where ' + quotename(#search) + N'=''1''';
exec sp_executesql #sql;
See The Curse and Blessings of Dynamic SQL
It is indeed possible, altough is often frowned upon.
Have a look at sp_executesql
Declare #search varchar(80)
set #search = 'RegionID'
declare #query varchar(max)
set #query = "Select * from TBL_TripDetails Where " + #search + " = '1'"
exec #query
DECLARE #search VARCHAR(80)
DECLARE #SQL VARCHAR(8000)
SET #search = 'RegionID'
SET #SQL = 'SELECT * FROM TBL_TripDetails WHERE ' + #search + ' = 1'
EXEC #SQL
Be careful though. Concatenating SQL can allow SQL injection attacks.
I'm a bit confused with your question "pass it any string, which it will be able to search upon". In your example your passing in a field which is being compared against a hard coded value of 1, this doesn't really match your description.
If this is truly what you wanted, then you'll need to use Dynamic SQL. If you just want to be able to support optional search criteria/parameters (e.g. If RegionID has a value set then apply criteria, else ignore criteria), then use the example below.
DECLARE #RegionID AS VARCHAR(1);
SELECT *
FROM TABLE
WHERE (#RegionID Is Null OR #RegionID = '' OR RegionID = #RegionID);
Now, if #RegionID is blank or NULL it won't be used in the criteria.
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