I have the following statement:
DECLARE #Nr_Karton int;
SELECT #Nr_Karton = ISNULL(MAX(Nr), 1000) FROM W_Karton;
SET #Nr_Karton = #Nr_Karton + 1;
INSERT INTO W_Karton (Container_ID, Nr, Beschrieb, CreationDate, Location)
VALUES ('1', #Nr_Karton, '', getDate(), 'Bösingen');
But I get the error:
[SQL] SELECT #Nr_Karton = ISNULL(MAX(Nr), 1000) FROM W_Karton
[Err] 42000 - [SQL Server]Must declare the scalar variable "#Nr_Karton".
How to get rid of the error?
I did some playing with this. The fictional schema I created was:
CREATE TABLE W_Karton (Container_ID int, Nr int, Beschrieb varchar(1),
CreationDate datetime, Location varchar(10))
Whilst it parsed and ran fine on my local 2008R2 box, the same code did not work when pasted into a SQL Fiddle.
However, if you remove all the semi-colons apart from the last one as per this SQL Fiddle you can see it seems to work fine!
I believe it shouldn't make any difference, but if you would rather it worked and don't care about the why, give it a try...
I encountered the same issue. It turns out it is due to ';' being selected as the "Query Terminator". IN SQL Fiddle, this actually means "batch terminator". There should be a drop-down button on the bottom right that has the text "[;]". Click that and select "Keyword [GO]".
Related
Newbie here. Attempting to allow report to run multiple values when being run but above error happens when selecting multiple. Any help will be appreciated.
where ContactActivityNoteType.ClientId = 1
and ContactActivityNoteType.ContactActivityNoteTypeId in (13, 4, 22)
and tc.ContactTypeId = 2
and ca.EnteredOn between #start_date and #end_date
and ca.ClientAccountId in (#ClientAccountId)
One option is to change your multi-valued parameter to a temporary table and then join that temp table to your main table.
In your query based dataset, you can do this part before main query.
For example, if following is your multi-valued variable:
DECLARE #ClientAccountId VARCHAR(MAX) = 'a10001,a10002,a10003,a10004'
You can use the following chunk of SQL code to change it to a temp table:
CREATE TABLE #ClientAccountIds (ClientAccountId VARCHAR(30));
DECLARE #Insert VARCHAR(MAX) = 'INSERT INTO #ClientAccountIds VALUES ('''+REPLACE(#ClientAccountId,',','''),(''')+''');';
EXEC (#Insert);
So that following SQL:
SELECT ClientAccountId FROM #ClientAccountIds
will return:
And now you can easily join this temporary table to your main query.
Hope this help?
I'm trying to create a function that takes the parameters for the column, the table, the limit, and offset. Basically, I want to be able to get a specified number of rows data from a specified table from a specified column.
However, I'm unable to get the following code to work - I get several errors such as:
syntax error, unexpected SELECT, expecting ':' in: "create function get_banana(lim int, off int, tbl varchar(32), col varchar(32)) r"
syntax error, unexpected RETURN in: "return"
syntax error, unexpected END in: "end"
These errors seem kind of meaningless.
My code is as follows:
CREATE FUNCTION GET_BANANA(lim int, off int, tbl varchar(32), col varchar(32))
RETURNS TABLE (clm int)
BEGIN
PREPARE SELECT col FROM tbl LIMIT ? OFFSET ?;
RETURN EXEC (lim, off);
END;
I'd appreciate any help :) Thanks!
I see at least two issues
EXEC needs the identifier that is returned by PREPARE, e.g.:
sql>prepare select * from tables;
execute prepared statement using: EXEC 2(...)
sql>exec 2();
The function parameters tbl and col are string values. You cannot use them as table/column identifiers.
Having said that, I am not even sure if PREPARE can be used inside a function.
No, PREPARE is a top-level statement modifier.
Good afternoon folks.
I'll preface this with "this was a hard question to ask". I'm running into conversion errors when I think I've got that part covered. Obviously, I do not.
The situation: VARCHAR field with INT data in it, plus some random garbage strings that are causing conversion issues. Here's an example of what I'm trying to do.
DECLARE #MyTABLE TABLE (
Value VARCHAR(50) NOT NULL
);
-- insert some strings
INSERT INTO #MyTABLE (Value) VALUES('400'), ('H-100'), ('H-200'), ('500'),
('600'), ('H-300');
-- conversion fails for the actual strings
SELECT *
FROM #MyTABLE m
WHERE CAST(m.Value AS INT) BETWEEN 1 AND 1000;
-- what I THOUGHT would fix it, but doesn't...
SELECT *
FROM (SELECT * FROM #MyTABLE WHERE Value NOT LIKE 'H%') X
WHERE CAST(X.Value AS INT) BETWEEN 1 AND 1000;
I realize there are other ways that I can do this, such as inserting all BUT the bad data into a temp table and querying that, but I'd like to know why my query doesn't work and what I could do to fix it.
EDIT - This is for SQL 2008 R2
Thanks in advance!
It is an odd bit, if you notice it's the BETWEEN clause that kills it, because the WHERE isn't being evaluated when you think it should, you can use:
SELECT *
FROM #MyTABLE
WHERE CASE WHEN ISNUMERIC(Value)=1 THEN value ELSE 0 END
BETWEEN 1 AND 1000
Demo: SQL Fiddle
have a query relating to MS SQL Server.
I'm going to have to be vague with details and change or remove certain parts as i can't say whether the info is confidential or not, but I've written a query that searches for students with their training units spanning across semesters using report builder 2.0:
DS_spanning: (Main dataset)
SET DATEFORMAT dmy
SELECT
FIRST_NAME AS FirstName
,LAST_NAME AS LastName
,START_DATE AS StartDate
,END_DATE AS EndDate
,UNIT_TYPE AS UnitType
,TP_FULLNAME AS TrainingPost
,SEMESTER_YEAR AS SemesterYear
FROM AA_GPR_TU
WHERE TU_START_DATE < #checkdate //Checkdate returns the end date of the
AND TU_END_DATE > #checkdate // selected semester
ORDER BY TU_START_DATE
PM_checkdate: (Dataset that #checkdate is linked to)
SET DATEFORMAT dmy
SELECT
new_semesterenddate
,new_semesterstartdate
,new_semesternumber
,new_semesteryear
,new_name
FROM
FilteredNew_rtpsemester
WHERE new_semesteryear >= 2004
ORDER BY new_semesterenddate DESC
Now, this works fine and does the job i want it to, however i can only select one semester at a time. When i try to tick the 'Allow Multiple Values' box under the Report Parameter Properties for #checkdate, running the report with more than one semester selected gives me this error:
Incorrect syntax near ','.
Query execution failed for dataset 'DS_spanning'.
An error has occurred during report processing.
An error occurred during local report processing.**
(The problem with a ',' is because when i select multiple values for the report, it supplies them to #checkdate as data1, data2, data3... etc.)
Is there something wrong with the way my parameter has been written, or do i need to change my query to accomodate multiple values?
Easiest way i could think of doing this would be using an IN statement in the section
WHERE TU_START_DATE < #checkdate AND TU_END_DATE > #checkdate
but i'm not sure how to use an IN statement in conjunction with and operands.
Any ideas folks?
i have had select multiple value problem so many times and after searching the internet for numerous hours i found this and it works a treat.
First of all create this function call split into the database you are running your queries from.
USE [DatabaseName]
GO
/****** Object: UserDefinedFunction [dbo].[split] Script Date: 07/19/2013 10:49:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[split](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END
the way you then use this in a WHERE clause is by using this line of code be sure to change the word column and parameter leave the word val as this is needed for the function
WHERE [COLUMN] IN (SELECT val FROM dbo.split(#Parameter, ','))
There will be no restrictions on using the same dataset for more than one paramater.
You should use 2 paramaters for this report, say #checkdate1 and #checkdate2, as this enables more control over what is used and where.
Okay, I'm getting this error when I try to execute this procedure. The thing is I'm not trying to convert to a bit at any time. At least not on purpose. I'm a bit stumped at the moment.
Declare #AValue varchar(max)
set #AValue = (SELECT Value
FROM dbo.Tbl
WHERE Name=#FILE
AND Value LIKE (CAST(#MODID as varchar(15))+'|%'))
set #AValue = PARSENAME(REPLACE(#AValue, '|', '.'), 1) -- Hack way to parse.
INSERT INTO dbo.Tbl
(
Name,
Value,
Type,
CDT,
UDT,
Active,
User
)
VALUES
(
'Agreement',
(CAST(#MODID AS varchar(15)) + '|' + #AValue),
'Download',
GETDATE(),
GETDATE(),
1,
#USER
)
Check the triggers on the tables, particularly the insert. Lots of times unexplainable errors can lurk there.
Post the error, the CREATE PROCEDURE statement, and - most importantly - the call to the procedure that is failing. Also, what version of SQL Server are you using?
Most likely, the stored proc has a parameter of type BIT, and you are calling the procedure with a value like 'F', '-1' or some other string that can't be converted to BIT.
Sorry, found the answer. I came back today and the error I was getting was completely different than the one I had when I first asked the question. Sorry I forgot to write that error.
Problem was my WHERE clause was getting multiple returns from the database cause I had been testing a lot, so there were duplicate rows.
GetDate needs to be assigned to something in T-SQL before it can be used in a insert.
Try this:
DECLARE #CDT DateTime
DECLARE #UDT DateTime
SELECT #CDT = GetDate()
SELECT #UDT = GetDate()
INSERT INTO dbo.Tbl
(
[Name],
[Value],
[Type],
CDT,
UDT,
Active,
User
)
VALUES
(
'Agreement',
(CAST(#MODID AS varchar(15)) + '|' + #AValue),
'Download',
#CDT,
#UDT,
1,
#USER
)