What's the purpose of SQL keyword “AS”? [closed] - sql-server

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am wondering about what AS Keyword do in SQL Server.
I know it's context when it is used on a query that it sets up an alias, however, I do not know what it means when it's used in stored procedures or User Defined Functions. Why is it needed before the begin keyword?
CREATE FUNCTION dbo.UDF_rangeoddeven( #start int, #end int, #oddeven nvarchar(4))
returns #table table
(
Number int
)
AS
BEGIN
IF #oddeven = 'even'
WHILE #start <= #end
BEGIN
IF #start%2 = 0
BEGIN
INSERT INTO #table
SELECT #start;
END
SET #start = #start + 1;
END
ELSE
WHILE #start <= #end
BEGIN
IF #start%2 = 1
BEGIN
INSERT INTO #table
SELECT #start;
END
SET #start = #start + 1;
END
RETURN
END
GO

It's a hunk of language syntax.
For stored functions / procedures (sps), common table expressions (CTEs), and views, AS works as part of the declaration syntax. Think of it this way: declare public_part AS private part.
The public part of an sp is its declaration: how to access it. The private part is the code. The same is true of a CTE:
WITH summary AS (
SELECT id, MAX(val) maxval, MIN(val) minval, SUM(val) sumval
FROM raw
GROUP BY ID
)
The grammar is reversed from the way it's used in SELECTs, in which it's declare expression AS name.
Why is it reversed? Maybe Dr. Stonebraker or Dr. Date know?
Some SQL dialects allow AS to be omitted in some contexts.

Related

Select top 1 from temp table returns only first character [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In a T-SQL code block, I am populating a temp table and doing a WHILE loop. In the WHILE loop, when I do a SELECT TOP 1 for a varchar value, it returns only the first character.
Here is the code
BEGIN
DECLARE #RowCounter int;
SET #RowCounter = 0;
DECLARE #TotalRows int;
SET #TotalRows = 0;
DECLARE #tempPcsDataId int;
SET #tempPcsDataId = 0;
-- create a temp table
-- to stack people: PalletLicensePlate in the Db is varchar(50) so I make tempPalletLicensePlate the same
DECLARE #DistinctPalletsTempTable TABLE
(
DeliveryDate datetime,
tempPalletLicensePlate varchar(50),
StoreNumber nvarchar(50),
DerivedWmsCode nvarchar(20),
ShipperClid int,
CartonCount int
);
-- populate the temp table
INSERT #DistinctPalletsTempTable
SELECT DISTINCT
DeliveryDate, PalletLicensePlate, StoreNumber,
DerivedWmsCode, ShipperClid, 0
FROM
PcsData
WHERE
InsertGuid = '017DA918-3AF3-4F86-949C-C2611E2BEEE8';
SET #TotalRows = (SELECT COUNT(*) FROM #DistinctPalletsTempTable);
WHILE #TotalRows >= #RowCounter
BEGIN
DECLARE #CartonCountForThisPallet int;
SET #CartonCountForThisPallet = 0;
DECLARE #ThisLicensePlate varchar;
SET #ThisLicensePlate = (SELECT TOP 1 tempPalletLicensePlate
FROM #DistinctPalletsTempTable);
SELECT #ThisLicensePlate -- this always returns B The first character
SET #CartonCountForThisPallet = (SELECT COUNT(*)
FROM PcsData
WHERE PalletLicensePlate = #ThisLicensePlate);
UPDATE #DistinctPalletsTempTable
SET CartonCount = #CartonCountForThisPallet;
SELECT #RowCounter;
SELECT #TotalRows;
SET #RowCounter = #RowCounter + 1;
END
SELECT * FROM #DistinctPalletsTempTable;
END
Here is a picture of select * from #DistinctPalletsTempTable; in the code above. You can see that tempPalletLicensePlate is a long string
How can I grab the complete tempPalletLicensePlate from the TOP 1 row?
Well - if you omit any length specification, a SQL variable declare as just varchar just default to 1 character length - this is defined, well documented behavior:
When n isn't specified in a data definition or variable declaration statement, the default length is 1
so no surprise here, really....
And the solution is really simple, too - always explicitly define a length when using varchar as a datatype - for a variable, or a parameter ....
DECLARE #ThisLicensePlate VARCHAR(50); -- **DEFINE** then length here!
SELECT TOP 1 #ThisLicensePlate = tempPalletLicensePlate
FROM #DistinctPalletsTempTable;
Now your #ThisLicensePlate will properly show the whole contents of the license plate! The problem really isn't the SELECT TOP 1.... part - it's the declaration of your SQL variable

Incorrect syntax near AS - SQL Server stored procedure [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I can't create this stored procedure, the error tells me that the syntax of AS is incorrect. Please help! I have searched everywhere where my error could be or how I can redefine the stored procedure, and I have not had success.
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[PRC_BizAgi_Obtener_Anualidad]')
AND type in (N'P'))
BEGIN
DROP PROCEDURE [dbo].[PRC_BizAgi_Obtener_Anualidad]
END
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PRC_BizAgi_Obtener_Anualidad]
#id_NinoCentro INT
AS
DECLARE #periodo INT
SET #periodo = YEAR(GETDATE())
/*SET #id_NinoCentro = ncp.id_Nino;*/
AS <-------- INCORRECT SYNTAX
BEGIN
SET NOCOUNT ON;
SELECT
ncp.id_NinoCentro,
CAST (MAX(ncp.Ano) AS VARCHAR)+''+
CASE
WHEN MAX(ncp.Mes) > 9
THEN CAST(MAX(ncp.Mes) AS VARCHAR)
ELSE '0'+ CAST(MAX(ncp.Mes) AS VARCHAR)
END AS periodo
FROM
nino_centro_pago ncp
WHERE
periodo = #periodo
AND ncp.id_NinoCentro = #id_NinoCentro
AND ProductoFlex = '101'
AND PagaInscr = 1
GROUP BY
ncp.id_NinoCentro
HAVING
COUNT(*) >= 6
END
Right after the parameters, you should have AS ... BEGIN ... and that's all - right now, you have the AS twice - right after the parameters, and again after declaring and setting the #periodo variable - you should have one AS only:
CREATE PROCEDURE [dbo].[PRC_BizAgi_Obtener_Anualidad]
#id_NinoCentro INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #periodo INT
SET #periodo = YEAR(GETDATE())
-- rest of your procedure here....
END

Find specific ResultSet in stored procedure using sql query or sp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
i have one sp with multiple resultsets like
Create procedure spNAME
As
Begin
select * from t1
select * from t2
select * from t3
END
now i want to create one stored procedure to find result of 3 statement in sp
Re-write your proc something like this..
Create procedure spNAME
#RS INT = NULL
As
Begin
IF (#RS = 1)
BEGIN
select * from t1
END
IF (#RS = 2)
BEGIN
select * from t2
END
IF (#RS = 3)
BEGIN
select * from t3
END
END
Now pass different parameter values to proc depending on what result set you want to return
Exec spNAME --<-- No Result set
Exec spNAME 1 --<-- Result set 1
Exec spNAME 2 --<-- Result set 2
Exec spNAME 3 --<-- Result set 3

I got request in SQL server as stating below [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
For example I have table like
Id name age
01 Praveen 20
02 mahesh 40
03 phani 50
I want see output like
01,02,03
Use For xml path() trick to do this. Considering that ID is of integer type else remove the convert function
SELECT Stuff((SELECT ',' + CONVERT(VARCHAR(20), Id)
FROM Yourtable
FOR xml path('')), 1, 1, '')
use cursor to fetch each id and concatenate them to a string
DECLARE cur cursor FAST_FORWARD READ_ONLY
FOR
SELECT id
FROM tbl
OPEN cur
DECLARE #x varchar(10)=''
DECLARE #d int
FETCH NEXT FROM cur INTO #d
WHILE ##FETCH_STATUS=0
BEGIN
SET #x=#x+convert(varchar(10),#d)+','
FETCH NEXT FROM cur INTO #d
END
Close cur
DEALLOCATE cur
SELECT left(#x,len(#x)-1)

Create a stored procedure which will generate alphanumeric with auto increment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to display a label field with system generated value i.e alphanumeric value.So
is it possible to create a stored procedure which will return alphanumeric value, with auto increment value every time that it is executed.
where the alpha value will be constant like "ABC" only the numeric value will be incremented.
For example:
1st time => ABC12345
2nd time => ABC12346
and so on.
Create FUNCTION instead of Stored Procedure
CREATE FUNCTION USF_GenerateNewID() RETURNS VARCHAR(10)
AS
BEGIN
DECLARE #Prefix VARCHAR(3) = 'ABC'
DECLARE #ID VARCHAR(10)
SET #ID = (SELECT TOP 1 ID FROM <TABLE> ORDER BY ID DESC)
SET #ID = #Prefix + CAST((CAST(REPLACE(#ID,#Prefix,'') AS INT) + 1) AS VARCHAR(10))
RETURN #ID
END

Resources