SQL Server CE Cast/Convert Double to String - vb.net

This may seems like a stupid question for most, but it has been bugging me for quite a while.
How do we concat a string and an integer in SQL Server CE?
FYI, I am using Vb.Net and Visual Studio 2010 Query Builder.
I tried
SELECT CONVERT(VARCHAR(10), mi.qty) FROM MutationItem mi
and
SELECT CAST(qty AS VARCHAR(10)) AS Expr1 FROM MutationItem mi
and
SELECT CAST(qty AS VARCHAR) AS Expr1 FROM MutationItem mi
with no luck.
The latter gives me an error :
Error in list of function arguments: 'AS' not recognized. Unable to
parse query text.
Please give me a hand on this.
Thanks !

Sorry guys, it's my bad.
Or actually it's the wizard's bad.
So I tried to push it even though it gives me an error, and it worked eventually.
My guess is that the table relation designer cant replicate CAST or CONVERT, and then giving me an alert about that.
Cheers !

I skipped this problem Visual Studio create a function with the code which throws problems
for example this code sql on sybase
CREATE FUNCTION GetV(#cod NUMERIC(8))
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE #result VARCHAR(20)
DECLARE #query VARCHAR(100)
SET #query = (SELECT p.v1+' '+cast(p.v2 AS VARCHAR)+'X'+cast(p.v3 AS VARCHAR) FROM table1 p WHERE p.cod=#cod)
IF(#query IS NULL OR #query = '' OR #query = ' ')
SET #result = 0
ELSE
SET #result = #query
RETURN #result
END
GO

Related

IN with Varchar is not working sql server

Below code is throwing error
declare #test varchar(100)='20,201,202,288'
SELECT * from Business where Businessid in (#test)
i.e.
Conversion failed when converting the varchar value '20,201,202,288' to data type int.
how can i make it working, i'm not getting, might be my mind is not able think any more..
You can use string_split():
select *
from Business
where Businessid in (select value from string_split(#test, ','));
You are confusing a string with a list of values in an in list. They are not the same thing.
We can use string_split in SQL Server 2016 and later versions only so I choose dynamic query for any version with more flexibility
DECLARE #test VARCHAR(100) = '20,201,202,288', #sql VARCHAR(250)
SET #sql = '
SELECT *
FROM Business
WHERE Businessid IN (' + #test + ')'
EXEC(#sql)

Pass String into #Parameter from a VS report

I did ask a question about this but still cant work out how to get this working, ive looked at some examples where people have used functions, table variables, create types and cant really get any working so wondering if someone could help and maybe explain a little bit of the code they write if its complicated.
Im using Visual studio 2012 to create reports and have on the report a drop down list populated with company names that a user can tick to view info about each of the companies.
What I want to do is get all the company IDs from this drop down and pass it into an In clause in my sql where statement. This is a simplified version of what I have got, im new to this so just trying to see what works for when I have to look at more complex stuff in the future.
Ideally the line ive comented out will be the line that should be used and the values passed into this, but ive added the equivalent line below which I have been using for testing, I get an error on the comma between the 1,2 and
error message syntax error near ','.
If someone can help with how to get this to work using the #companynameParam I have comented out that would be great. CompanyNameParam is the name of the drop down on the VS report.
Declare #ContactID int
--set #ContactID = #CompanyNameParam
set #ContactID = 1,2,3,4,5,6,7,8,9
select CompanyName as 'reportcompanyname'
from company co inner join contacts c on c.CompanyID = co.CompanyID
where ContactID in (#ContactID);
You are getting an error because SET command is used to assign single / scalar value to a single variable at a time and you are trying to assign multiple comma separated string values to a single integer variable #ContactID in one go.
Correct approach is to first declare a local variable of type varchar and not Int as
#CompanyNameParam must be a string.
Declare #ContactID varchar(500);
Then convert comma separated string into a table. [There can be many ways to do this] I'm just giving an example. Create a user defined function as:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CSVToTable] (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE
(id int not null)
AS
BEGIN
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab(id) VALUES (#VALUE)
END
RETURN
END
GO
Once done you can re-write the sproc as:
select CompanyName as 'reportcompanyname'
from company co inner join contacts c on c.CompanyID = co.CompanyID
where ContactID in (SELECT * FROM dbo.CSVToTable(#CompanyNameParam));
Check DEMO here..

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'.

Must declare the scalar variable

#RowFrom int
#RowTo int
are both Global Input Params for the Stored Procedure, and since I am compiling the SQL query inside the Stored Procedure with T-SQL then using Exec(#sqlstatement) at the end of the stored procedure to show the result, it gives me this error when I try to use the #RowFrom or #RowTo inside the #sqlstatement variable that is executed.. it works fine otherwise.. please help.
"Must declare the scalar variable "#RowFrom"."
Also, I tried including the following in the #sqlstatement variable:
'Declare #Rt int'
'SET #Rt = ' + #RowTo
but #RowTo still doesn't pass its value to #Rt and generates an error.
You can't concatenate an int to a string. Instead of:
SET #sql = N'DECLARE #Rt int; SET #Rt = ' + #RowTo;
You need:
SET #sql = N'DECLARE #Rt int; SET #Rt = ' + CONVERT(VARCHAR(12), #RowTo);
To help illustrate what's happening here. Let's say #RowTo = 5.
DECLARE #RowTo int;
SET #RowTo = 5;
DECLARE #sql nvarchar(max);
SET #sql = N'SELECT ' + CONVERT(varchar(12), #RowTo) + ' * 5';
EXEC sys.sp_executesql #sql;
In order to build that into a string (even if ultimately it will be a number), I need to convert it. But as you can see, the number is still treated as a number when it's executed. The answer is 25, right?
In your case you can use proper parameterization rather than use concatenation which, if you get into that habit, you will expose yourself to SQL injection at some point (see this and this:
SET #sql = #sql + ' WHERE RowNum BETWEEN #RowFrom AND #RowTo;';
EXEC sys.sp_executesql #sql,
N'#RowFrom int, #RowTo int',
#RowFrom, #RowTo;
You can also get this error message if a variable is declared before a GOand referenced after it.
See this question and this workaround.
Just FYI, I know this is an old post, but depending on the database COLLATION settings you can get this error on a statement like this,
SET #sql = #Sql + ' WHERE RowNum BETWEEN #RowFrom AND #RowTo;';
if for example you typo the S in the
SET #sql = #***S***ql
sorry to spin off the answers already posted here, but this is an actual instance of the error reported.
Note also that the error will not display the capital S in the message, I am not sure why, but I think it is because the
Set #sql =
is on the left of the equal sign.
Sometimes, if you have a 'GO' statement written after the usage of the variable, and if you try to use it after that, it throws such error. Try removing 'GO' statement if you have any.
This is most likely not an answer to the issue itself, but this question pops up as first result when searching for Sql declare scalar variable hence I want to share a possible solution to this error.
In my case this error was caused by the use of ; after a SQL statement. Just remove it and the error will be gone.
I guess the cause is the same as #IronSean already posted in a comment above:
it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.
For example:
DECLARE #id int
SET #id = 78
SELECT * FROM MyTable WHERE Id = #var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = #var
Just adding what fixed it for me, where misspelling is the suspect as per this MSDN blog...
When splitting SQL strings over multiple lines, check that that you are comma separating your SQL string from your parameters (and not trying to concatenate them!) and not missing any spaces at the end of each split line. Not rocket science but hope I save someone a headache.
For example:
db.TableName.SqlQuery(
"SELECT Id, Timestamp, User " +
"FROM dbo.TableName " +
"WHERE Timestamp >= #from " +
"AND Timestamp <= #till;" + [USE COMMA NOT CONCATENATE!]
new SqlParameter("from", from),
new SqlParameter("till", till)),
.ToListAsync()
.Result;
Case Sensitivity will cause this problem, too.
#MyVariable and #myvariable are the same variables in SQL Server Man. Studio and will work. However, these variables will result in a "Must declare the scalar variable "#MyVariable" in Visual Studio (C#) due to case-sensitivity differences.
Just an answer for future me (maybe it helps someone else too!). If you try to run something like this in the query editor:
USE [Dbo]
GO
DECLARE #RC int
EXECUTE #RC = [dbo].[SomeStoredProcedure]
2018
,0
,'arg3'
GO
SELECT month, SUM(weight) AS weight, SUM(amount) AS amount
FROM SomeTable AS e
WHERE year = #year AND type = 'M'
And you get the error:
Must declare the scalar variable "#year"
That's because you are trying to run a bunch of code that includes BOTH the stored procedure execution AND the query below it (!). Just highlight the one you want to run or delete/comment out the one you are not interested in.
If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:
I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.
Due to the generated export, there have been a bunch of "GO" statements in the sql file.
What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!
As stated in https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go?view=sql-server-ver16 , the scope of a user-defined variable is batch dependent .
--This will produce the error
GO
DECLARE #MyVariable int;
SET #MyVariable = 1;
GO --new batch of code
SELECT #MyVariable--CAST(#MyVariable AS
int);
GO
--This will not produce the error
GO
DECLARE #MyVariable int;
SET #MyVariable = 1;
SELECT #MyVariable--CAST(#MyVariable AS int);
GO
We get the same error when we try to pass a variable inside a dynamic SQL:
GO
DECLARE #ColumnName VARCHAR(100),
#SQL NVARCHAR(MAX);
SET #ColumnName = 'FirstName';
EXECUTE ('SELECT [Title],#ColumnName FROM Person.Person');
GO
--In the case above #ColumnName is nowhere to be found, therefore we can either do:
EXECUTE ('SELECT [Title],' +#ColumnName+ ' FROM Person.Person');
or
GO
DECLARE #ColumnName VARCHAR(100),
#SQL NVARCHAR(MAX);
SET #ColumnName = 'FirstName';
SET #SQL = 'SELECT ' + #ColumnName + ' FROM Person.Person';
EXEC sys.sp_executesql #SQL
GO
Give a 'GO' after the end statement and select all the statements then execute

SQL Server 2005: Determine datatype of variable

Is it possible to determine the type of a local variable at runtime in TSQL?
For example, say I wanted to do something along these lines:
IF ( #value IS INTEGER )
Or
IF ( TYPEOF(#value) = <whatever> )
Does anyone know of any way to accomplish this?
EDIT: This is not for a specific task, this is more of a general knowledge question. I do appreciate answers that indicate that the type should be known since it is declared within the same batch, I am curious as to whether the type can be determined at runtime.
run this
declare #d int
select #d = 500
if cast(sql_variant_property(#d,'BaseType') as varchar(20)) = 'int'
print 'yes'
else
print 'no'
using SQL 2019 , below code still working
DECLARE #MyVar int;SET #MyVar = 99;
DECLARE #MyVarDataType varchar(50);
SET #MyVarDataType = cast(SQL_VARIANT_PROPERTY(#MyVar,'BaseType') AS varchar);
PRINT #MyVarDataType
I don't think so - BUT it is a local variable so are declaring it in the same procedure so you would know the type anyways - or am I missing something?