Identity column - asp.net

Stored Procedure
CREATE PROCEDURE [dbo].[Insert_Customer]
#id int,
#FName varchar(50) ,
#MName varchar(50) ,
#LName varchar(50) ,
#Age int ,
#Citizen varchar(50),
#Gender varchar(50) ,
#DOB varchar(50) ,
#Status varchar(50) ,
#Nationality varchar(50) ,
#Country varchar(50) ,
#State varchar(50) ,
#City varchar(50) ,
#Address varchar(MAX) ,
#Pin varchar(50) ,
#AccNo int IDENTITY (100,1),
#Branch varchar(50) ,
#IDProof varchar(50) ,
#IDNo varchar(50) ,
#IDName varchar(50) ,
#DOI varchar(50) ,
#Date datetime
AS
BEGIN
Insert into tbl_Customer1
values(#id,#FName,#MName,#LName,#Age,#Citizen,#Gender,#DOB,#Status,#Nationality)
Insert into tbl_Customer2
values(#id,#Country,#State,#City,#Address,#Pin,#accno ,#Branch)
Insert into tbl_Customer3
values(#id,#IDProof,#IDNo,#IDName,#DOI,#Date)
END
Here the error is
Msg 156, Level 15, State 1, Procedure Insert_Customer, Line 28
Incorrect syntax near the keyword 'IDENTITY'.
Msg 137, Level 15, State 2, Procedure Insert_Customer, Line 42
Must declare the scalar variable "#accno".
Msg 137, Level 15, State 2, Procedure Insert_Customer, Line 44
Must declare the scalar variable "#IDProof".

You cannot declare INT IDENTITY variable / parameter. If particular column defined as IDENTITY column, you don't have to add it's value insert statement. If you don't specify column value, identity number automatically will set.

#AccNo int IDENTITY (100,1),
you cant set a parameter as identity.
Why do you need it in the first place?
This should be only on your table.
Can you explain why do you need it so we can help you?

Related

create virtual column in mariadb with case statement fails

I am trying to create a table in MariaDB with a virtual column, defined by a case statement
This is what I have
create table Foto (
ID int AUTO_INCREMENT not null primary key,
LigPlaatsCode varchar(10) not null,
FotoTypeID int not null check (FotoType in (0, 1, 2, 3)),
Foto varchar(1000) not null,
FotoType varchar(50) as
case FotoTypeID
when 0 then 'Bidprent'
when 1 then 'Krantartikel'
when 2 then 'Persoon'
else 'Graf'
end, `
constraint FK_Foto_LigPlaats foreign key (LigPlaatsCode) references LigPlaats (LigPlaatsCode)
)
however it always gives me this error
#42000You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'case FotoTypeID
when 0 then 'Bidprent'
when 1 then 'Krantar' at line 7
When I google on how to create virtual column and case, the links I found seem to suggest I got it right, but obviously I dont. So I am missing something.
What is wrong with this create table statement ?
EDIT
my version is 10.3.21-MariaDB
Generated column requires parantehese around case expression:
create table Foto (
ID int AUTO_INCREMENT not null primary key,
LigPlaatsCode varchar(10) not null,
FotoTypeID int not null ,
Foto varchar(1000) not null,
FotoType varchar(50) as
(case FotoTypeID
when 0 then 'Bidprent'
when 1 then 'Krantartikel'
when 2 then 'Persoon'
else 'Graf'
end), -- brackets around
-- constraint as separate entry because it is referencing FotoType
constraint fototypecheck check (FotoType in (0, 1, 2, 3))
);
db<>fiddle demo
This line does not make sense as FotoType is text:
FotoTypeID int not null check (FotoType in (0, 1, 2, 3)),
-- probably it should be
FotoTypeID int not null check (FotoTypeID in (0, 1, 2, 3)),

user defined data types allowed in testing views?

I'm using tsqlt to test a view -- OrderHeader, which joins OrderHeader with OrderState. In a set up procedure I create fake tables for those two tables, and insert rows. The table defs and user defined data types are below.
When I run the tsqt procedure I've written to test the views, I create an expected table
CREATE TABLE expected_v_ctOrderHeader
(
[countOrderNumber] dbo.orderNumber NOT NULL
,[orderId] dbo.id NOT NULL
,[orderType] dbo.orderType NOT NULL
,[orderClass] dbo.orderClass NOT NULL
,[orderState] dbo.orderState NOT NULL
,[site] dbo.site NOT NULL
,[region] [dbo].[region] NULL
,[currentInstance] INT NOT NULL
,[prOrderId] [dbo].[id] NULL
,[description] dbo.description NULL
,[isSoftCount] BIT NOT NULL
,[dtDue] DATETIMEOFFSET NULL
,[orderMethod] [dbo].[orderMethod] NOT NULL
,[availableForCounting] BIT NOT NULL
);
Insert into it the same data as in the SetUp procedure:
INSERT INTO dbo.expected_v_ctOrderHeader
(
[countOrderNumber]
,[orderId]
,[orderType]
,[orderClass]
,[orderState]
,[site]
,[region]
,[currentInstance]
,[prOrderId]
,[description]
,[isSoftCount]
,[dtDue]
,[orderMethod]
,[availableForCounting]
)
VALUES
('10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'1'
,'1/1/2020'
,'10'
,'1')
,('100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'1'
,'2/1/2020'
,'100'
,'0')
,('200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'0'
,'3/1/2020'
,'200'
,'1')
Do an EXEC tsqlt.AssertEqualsTable
EXEC tSQLt.AssertEqualsTable
#Expected = N'dbo.expected_v_ctOrderHeader'
, #Actual = N'dbo.v_ctOrderHeader'
The base tables are defined using user defined types as follows:
The UDTs are as follows:
[dbo].[orderNumber] VARCHAR(50)
[dbo].[id] INT
[dbo].[orderType] NVARCHAR(50)
[dbo].[orderClass] NVARCHAR(50)
[dbo].[orderState] NVARCHAR(50)
[dbo].[site] VARCHAR(50)
[dbo].[region] VARCHAR(50)
[dbo].[description] NVARCHAR(500)
[dbo].[orderMethod] NVARCHAR(50)
The view definition is:
SELECT ch.[countOrderNumber] --[dbo].[orderNumber]
,ch.[orderId] --[dbo].[id]
,ch.[orderType] --[dbo].[orderType]
,ch.[orderClass] --[dbo].[orderClass]
,ch.[orderState] --[dbo].[orderState]
,ch.[site] --[dbo].[site]
,ch.[region] --[dbo].[region]
,ch.[instance] AS currentInstance --INT
,ch.[prOrderId] --[dbo].[id]
,ch.[description] --[dbo].[description]
,ch.[isSoftCount] --BIT
,ch.[dtDue] --DATETIMEOFFSET
,ch.[orderMethod] --[dbo].[orderMethod]
,cs.[availableForCounting]--BIT
FROM [dbo].[ctOrderHeader] ch
INNER JOIN [dbo].[ctOrderState] cs ON ch.orderState = cs.orderState
--tsql
CREATE TABLE [dbo].[ctOrderHeader](
[countOrderNumber] [dbo].[orderNumber] NOT NULL,
[orderId] [dbo].[id] NOT NULL,
[orderType] [dbo].[orderType] NOT NULL,
[orderClass] [dbo].[orderClass] NOT NULL,
[orderState] [dbo].[orderState] NOT NULL,
[site] [dbo].[site] NOT NULL,
[region] [dbo].[region] NULL,
[instance] [int] NOT NULL,
[prOrderId] [dbo].[id] NULL,
[description] [dbo].[description] NULL,
[isSoftCount] [bit] NOT NULL,
[dtDue] [datetimeoffset](7) NULL,
[orderMethod] [dbo].[orderMethod] NOT NULL,
CONSTRAINT [PK_ctOrderHeader_countOrderNumber] PRIMARY KEY CLUSTERED
(
[countOrderNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UQ_ctOrderHeader_countOrderNumber] UNIQUE NONCLUSTERED
(
[countOrderNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[ctOrderState](
[orderState] [dbo].[orderState] NOT NULL,
[description] [dbo].[description] NOT NULL,
[displayName] [dbo].[displayName] NOT NULL,
[availableForCounting] [bit] NOT NULL,
CONSTRAINT [PK_ctOrderState_orderState] PRIMARY KEY CLUSTERED
(
[orderState] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--
The tsql test fails (it should pass), with the following message:
(1 row affected)
[v_ctOrderHeader].[Test Data] failed: (Failure) Unexpected/missing column(s)
One example 'missing' column is
|< countOrderNumber, with a system_type_id AND user_type_id as VARCHAR(50)
The actual countOrderNumber is system_type_id = VARCHAR(50) and user_type_id = dbo.orderNumber.
I have tried all permutations for creating the expected table (using the UDT, or not) and always get the same error.
I have also tried inserting into a temp table the results of the view:
SELECT * INTO #t FROM v_ctOrderHeader
EXEC tSQLt.AssertEqualsTable
#Expected = N'dbo.expected_v_ctOrderHeader' -- nvarchar(max)
, #Actual = #t
And get the identical errors (mismatches).
Have you tried creating both the actual and expected tables via SELECT .. INTO?
This will create both tables with exactly the same format and remove the column difference. Use TOP(0) for the expected table. An example test is:
CREATE OR ALTER PROC v_ctOrderHeader.[Test Data]
AS
--arrange
SELECT TOP (0)
*
INTO v_ctOrderHeader.Expected
FROM dbo.YourViewName;
--populate v_ctOrderHeader.Expected
EXEC tSQLt.FakeTable #TableName = N'dbo.ctOrderHeader';
EXEC tSQLt.FakeTable #TableName = N'dbo.ctOrderState';
--populate dbo.ctOrderHeader
--populate dbo.ctOrderState
--act
SELECT *
INTO v_ctOrderHeader.Actual
FROM dbo.YourViewName;
--assert
EXEC tSQLt.AssertEqualsTable #Expected = N'v_ctOrderHeader.Expected', -- nvarchar(max)
#Actual = N'v_ctOrderHeader.Actual', -- nvarchar(max)
#Message = N'', -- nvarchar(max)
#FailMsg = N''; -- nvarchar(max)
I am unable to recreate the problems you are seeing and am able to run th test you have provided without error, i.e. it passes as expected.
For reference, I am running SQL2017 and tSQLt 1.0.5873.27393.
This is my code (all in one block for ease):
--!
--! Create base objects
--!
CREATE TYPE [dbo].[orderNumber] FROM varchar(50) ;
CREATE TYPE [dbo].[id] FROM int ;
CREATE TYPE [dbo].[orderType] FROM nvarchar(50) ;
CREATE TYPE [dbo].[orderClass] FROM nvarchar(50) ;
CREATE TYPE [dbo].[orderState] FROM nvarchar(50) ;
CREATE TYPE [dbo].[site] FROM varchar(50) ;
CREATE TYPE [dbo].[region] FROM varchar(50) ;
CREATE TYPE [dbo].[description] FROM nvarchar(500) ;
CREATE TYPE [dbo].[orderMethod] FROM nvarchar(50) ;
CREATE TYPE [dbo].[displayName] FROM nvarchar(128) ;
GO
CREATE TABLE [dbo].[ctOrderState](
[orderState] [dbo].[orderState] NOT NULL,
[description] [dbo].[description] NOT NULL,
[displayName] [dbo].[displayName] NOT NULL,
[availableForCounting] [bit] NOT NULL,
CONSTRAINT [PK_ctOrderState_orderState] PRIMARY KEY CLUSTERED
(
[orderState] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ctOrderHeader](
[countOrderNumber] [dbo].[orderNumber] NOT NULL,
[orderId] [dbo].[id] NOT NULL,
[orderType] [dbo].[orderType] NOT NULL,
[orderClass] [dbo].[orderClass] NOT NULL,
[orderState] [dbo].[orderState] NOT NULL,
[site] [dbo].[site] NOT NULL,
[region] [dbo].[region] NULL,
[instance] [int] NOT NULL,
[prOrderId] [dbo].[id] NULL,
[description] [dbo].[description] NULL,
[isSoftCount] [bit] NOT NULL,
[dtDue] [datetimeoffset](7) NULL,
[orderMethod] [dbo].[orderMethod] NOT NULL,
CONSTRAINT [PK_ctOrderHeader_countOrderNumber] PRIMARY KEY CLUSTERED
(
[countOrderNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UQ_ctOrderHeader_countOrderNumber] UNIQUE NONCLUSTERED
(
[countOrderNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
IF OBJECTPROPERTYEX(OBJECT_ID(N'[dbo].[v_ctOrderHeader]'), N'IsView') = 1
DROP VIEW [dbo].[v_ctOrderHeader]
GO
CREATE OR ALTER VIEW [dbo].[v_ctOrderHeader]
AS
SELECT ch.[countOrderNumber] --[dbo].[orderNumber]
,ch.[orderId] --[dbo].[id]
,ch.[orderType] --[dbo].[orderType]
,ch.[orderClass] --[dbo].[orderClass]
,ch.[orderState] --[dbo].[orderState]
,ch.[site] --[dbo].[site]
,ch.[region] --[dbo].[region]
,ch.[instance] AS currentInstance --INT
,ch.[prOrderId] --[dbo].[id]
,ch.[description] --[dbo].[description]
,ch.[isSoftCount] --BIT
,ch.[dtDue] --DATETIMEOFFSET
,ch.[orderMethod] --[dbo].[orderMethod]
,cs.[availableForCounting]--BIT
FROM [dbo].[ctOrderHeader] ch
INNER JOIN [dbo].[ctOrderState] cs ON ch.orderState = cs.orderState
GO
--!
--! Create test objects
--!
EXEC tSQLt.NewTestClass #ClassName = N'StackOverflowTests';
GO
IF OBJECTPROPERTYEX(OBJECT_ID(N'[StackOverflowTests].[SetUp]'), N'IsProcedure') = 1
DROP PROCEDURE [StackOverflowTests].[SetUp]
GO
CREATE PROCEDURE [StackOverflowTests].[SetUp]
AS
BEGIN
EXEC tSQLt.FakeTable #TableName = N'dbo.ctOrderState' ;
EXEC tSQLt.FakeTable #TableName = N'dbo.ctOrderHeader' ;
INSERT dbo.ctOrderState (orderState, [description] , displayName, availableForCounting)
VALUES (10, 'Not Specified 10', 'Number 10', 1 )
, (100, 'Not Specified 100', 'Number 100', 1 )
, (200, 'Not Specified 200', 'Number 200', 1 )
;
INSERT dbo.ctOrderHeader
(
countOrderNumber
, orderId
, orderType
, orderClass
, orderState
, site
, region
, instance
, prOrderId
, description
, isSoftCount
, dtDue
, orderMethod
)
VALUES
(
'10' -- countOrderNumber - orderNumber
, 10 -- orderId - id
, '10' -- orderType - orderType
, '10' -- orderClass - orderClass
, '10' -- orderState - orderState
, '10' -- site - site
, '10' -- region - region
, 10 -- instance - int
, 10 -- prOrderId - id
, '10' -- description - description
, 1 -- isSoftCount - bit
, '20200101' -- dtDue - datetimeoffset(7)
, '10' -- orderMethod - orderMethod
)
, (
'100' -- countOrderNumber - orderNumber
, 100 -- orderId - id
, '100' -- orderType - orderType
, '100' -- orderClass - orderClass
, '100' -- orderState - orderState
, '100' -- site - site
, '100' -- region - region
, 100 -- instance - int
, 100 -- prOrderId - id
, '100' -- description - description
, 1 -- isSoftCount - bit
, '20200102' -- dtDue - datetimeoffset(7)
, '100' -- orderMethod - orderMethod
)
, (
'200' -- countOrderNumber - orderNumber
, 200 -- orderId - id
, '200' -- orderType - orderType
, '200' -- orderClass - orderClass
, '200' -- orderState - orderState
, '200' -- site - site
, '200' -- region - region
, 200 -- instance - int
, 200 -- prOrderId - id
, '200' -- description - description
, 0 -- isSoftCount - bit
, '20200103' -- dtDue - datetimeoffset(7)
, '200' -- orderMethod - orderMethod
)
;
END
GO
IF OBJECTPROPERTYEX(OBJECT_ID(N'[StackOverflowTests].[test v_ctOrderHeader join conditione]'), N'IsProcedure') = 1
DROP PROCEDURE [StackOverflowTests].[test v_ctOrderHeader join condition]
GO
CREATE OR ALTER PROCEDURE [StackOverflowTests].[test v_ctOrderHeader join condition]
AS
BEGIN
CREATE TABLE expected_v_ctOrderHeader
(
[countOrderNumber] dbo.orderNumber NOT NULL
,[orderId] dbo.id NOT NULL
,[orderType] dbo.orderType NOT NULL
,[orderClass] dbo.orderClass NOT NULL
,[orderState] dbo.orderState NOT NULL
,[site] dbo.site NOT NULL
,[region] [dbo].[region] NULL
,[currentInstance] INT NOT NULL
,[prOrderId] [dbo].[id] NULL
,[description] dbo.description NULL
,[isSoftCount] BIT NOT NULL
,[dtDue] DATETIMEOFFSET NULL
,[orderMethod] [dbo].[orderMethod] NOT NULL
,[availableForCounting] BIT NOT NULL
);
-- INSERT into it the same data as in the SetUp procedure:
INSERT INTO dbo.expected_v_ctOrderHeader
(
[countOrderNumber]
,[orderId]
,[orderType]
,[orderClass]
,[orderState]
,[site]
,[region]
,[currentInstance]
,[prOrderId]
,[description]
,[isSoftCount]
,[dtDue]
,[orderMethod]
,[availableForCounting]
)
VALUES
('10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'10'
,'1'
,'20200101'
,'10'
,'1')
,('100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'100'
,'1'
,'20200102'
,'100'
,'1')
,('200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'200'
,'0'
,'20200103'
,'200'
,'1');
EXEC tSQLt.AssertEqualsTable
#Expected = N'dbo.expected_v_ctOrderHeader'
, #Actual = N'dbo.v_ctOrderHeader'
END
GO
--!
--! Run the tests
--!
EXEC tSQLt.Run 'StackOverflowTests';
GO
And this is the result I get:
+----------------------+
|Test Execution Summary|
+----------------------+
|No|Test Case Name |Dur(ms)|Result |
+--+----------------------------------------------------------+-------+-------+
|1 |[StackOverflowTests].[test v_ctOrderHeader join condition]| 47|Success|
-----------------------------------------------------------------------------
Test Case Summary: 1 test case(s) executed, 1 succeeded, 0 failed, 0 errored.
-----------------------------------------------------------------------------
Are you doing anything different in your test or setup than I am doing above? Maybe an older version of tSQLt?
Hope this helps

Getting error :Error(2,3): PL/SQL: SQL Statement ignored Error(8,5): PL/SQL: ORA-00984: column not allowed here

My code is like below.
create table XXINF_DB_OBJECT_DDL_LOG (
EVENT_DATE DATE NOT NULL,
EVENT_TIMESTAMP TIMESTAMP NOT NULL,
EVENT_TYPE VARCHAR2(30) NOT NULL,
OBJECT_TYPE VARCHAR2(30) NOT NULL,
OBJECT_OWNER VARCHAR2(30) NOT NULL,
OBJECT_NAME VARCHAR2(30) NOT NULL,
DB_USER VARCHAR2(30) NOT NULL,
OS_USER VARCHAR2(100) ,
HOST_NAME VARCHAR2(100),
HOST_IP_ADDRESS VARCHAR2(30)
);
create or replace trigger XXINF_DB_OBJECT_DDL_LOG_AUDIT
AFTER DDL ON schema
begin
insert into XXINF_DB_OBJECT_DDL_LOG values(
sysdate,
systimestamp,
ora_sysevent,
ora_dict_obj_type,
ora_dict_obj_owner,
ora_dict_odj_name,
ora_login_user,
SYS_CONTEXT('USERENV','OS_USER'),
SYS_CONTEXT('USERENV','TERMINAL'),
SYS_CONTEXT('USERENV','IP_ADDRESS')
);
END;
/
when I execute get error:
Error(2,3): PL/SQL: SQL Statement ignored Error(8,5): PL/SQL:
ORA-00984: column not allowed here
Please use the corrections as below:
create or replace trigger XXINF_DB_OBJECT_DDL_LOG_AUDIT
AFTER DDL ON SCHEMA
begin
insert into XXINF_DB_OBJECT_DDL_LOG
(
EVENT_DATE,
EVENT_TIMESTAMP,
EVENT_TYPE,
OBJECT_TYPE,
OBJECT_OWNER,
OBJECT_NAME,
DB_USER,
OS_USER,
HOST_NAME,
HOST_IP_ADDRESS
)
values
(
sysdate,
systimestamp,
ora_sysevent,
ora_dict_obj_type ,
ora_dict_obj_owner,
ora_dict_obj_name ,
ora_login_user ,
SYS_CONTEXT('USERENV','OS_USER'),
SYS_CONTEXT('USERENV','TERMINAL'),
SYS_CONTEXT('USERENV','IP_ADDRESS') );
END;
/

How do i display a count from another table in a gridview?

I building a blog for school i would like to display the count of comments for each thread made. However I'm a bit lost to how to achieve this goal any help would be great thank you!
i have 2 tables
CREATE TABLE `blog_message` (
`MessageID` int(30) NOT NULL AUTO_INCREMENT,
`Username` varchar(45) NOT NULL,
`Message` text,
`AddedDate` datetime DEFAULT NULL,
`Title` varchar(45) DEFAULT NULL,
PRIMARY KEY (`MessageID`)
)
CREATE TABLE `blog_comments` (
`CommentID` int(30) NOT NULL AUTO_INCREMENT,
`MessageID` int(30) DEFAULT NULL,
`Author` varchar(45) DEFAULT NULL,
`CommentMessage` text,
`AddedDate` datetime DEFAULT NULL,
PRIMARY KEY (`CommentID`),
KEY `blog_comments_ibfk_1` (`MessageID`),
CONSTRAINT `blog_comments_ibfk_1` FOREIGN KEY (`MessageID`) REFERENCES `blog_message` (`MessageID`)
)
my goal is
to display in a gridview
int a table format
Comment count | title | Username | Date of creation
The following is MySQL syntax, not sure what you're using. But this will return a list MessageIds and the number of comments they have.
----------------------------
| MessageId | comment_count|
----------------------------
| 1234 | 34 |
----------------------------
SELECT bm.MessageId, count(bc.CommentId) as comment_count
FROM blog_comments bc, blog_message bm
WHERE bm.MessageId = bc.MessageId
GROUP BY bm.MessageId
If you want the Author and AddedDate just add it to the SELECT statement (i.e. SELECT bm.MessageId, count(bc.CommentId) as comment_count, bm.AddedDate, bm.Author).
Try the following
SELECT
bm.MessageID, Count(bc.CommentID) as Cnt, Title, Username, AddedDate
FROM blog_message bm
LEFT OUTER JOIN blog_comments bc
ON bm.MessageID = bc.MessageID
GROUP BY bm.MessageID,Title, Username, AddedDate

passing list of name/value pairs to stored procedure

I have a name/value pair in a List<T> and needing to find the best way to pass these to a stored procedure.
Id Name
1 abc
2 bbc
3 cnn
....
...
What is the best way to accomplish this?
One way to handle this in SQL Server 2005 (prior to the availability of table valued parameters) was to pass a delimited list and use a Split function. If you are using a two-column array, you would want to use two different delimiters:
Declare #Values varchar(max)
Set #Values = '1,abc|2,bbc|3,cnn'
With SplitItems As
(
Select S.Value As [Key]
, S2.Value
, Row_Number() Over ( Partition By S.Position Order By S2.Position ) As ElementNum
From dbo.Split(#Values,'|') As S
Outer Apply dbo.Split(S.Value, ',') As S2
)
Select [Key]
, Min( Case When S.ElementNum = 1 Then S.Value End ) As ListKey
, Min( Case When S.ElementNum = 2 Then S.Value End ) As ListValue
From SplitItems As S
Group By [Key]
Create Function [dbo].[Split]
(
#DelimitedList nvarchar(max)
, #Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(#DelimitedList, Len(#Delimiter)) <> #Delimiter Then #Delimiter Else '' End
+ #DelimitedList
+ Case When Right(#DelimitedList, Len(#Delimiter)) <> #Delimiter Then #Delimiter Else '' End
As List
, Len(#Delimiter) As DelimiterLen
)
, Numbers As
(
Select Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(#Delimiter, CL.list, N.Value + 1)
- ( CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value < Len(CL.List)
And Substring(CL.List, N.Value, CL.DelimiterLen) = #Delimiter
)
Another way to handle this without table-valued parameters is to pass Xml as an nvarchar(max):
Declare #Values nvarchar(max)
Set #Values = '<root><Item Key="1" Value="abc"/>
<Item Key="2" Value="bbc"/>
<Item Key="3" Value="cnn"/></root>'
Declare #docHandle int
exec sp_xml_preparedocument #docHandle output, #Values
Select *
From OpenXml(#docHandle, N'/root/Item', 1)
With( [Key] int, Value varchar(10) )
Take a look at Arrays and Lists in SQL Server 2008 to get some ideas
SQL Server 2008 also supports this multi row values syntax
create table #bla (id int, somename varchar(50))
insert #bla values(1,'test1'),(2,'Test2')
select * from #bla
i endup using foreach <insert>
This could done through three ways.
User Defined Table Type
Json Object Parsing
XML Parsing
I tried with the first option and passed a list of pairs in User Defined Table Type. This works for me. I am posting here, it might help someone else.
The first challenge for me was to pass the list of key value pair data structure and second to loop through the list and insert the record in a table.
Step 1 : Create a User Defined Table Type. I have created with a name 'TypeMetadata'. As it is custom type, I created two attributes of type nvarchar. You can create one of type integer and second of type nvarchar.
-- Type: metadata ---
IF EXISTS(SELECT * FROM SYS.TYPES WHERE NAME = 'TypeMetadata')
DROP TYPE TypeMetadata
GO
CREATE TYPE TypeMetadata AS TABLE (
mkey nvarchar (50),
mvalue nvarchar (50)
);
GO
Step 2 : Then I created a stored procedure with name 'createfiled'
-- Procedure: createtext --
CREATE PROCEDURE [dbo].[createfield]
#name nvarchar(50),
#text nvarchar(50),
#order int,
#type nvarchar(50),
#column_id int ,
#tid int,
#metadataList TypeMetadata readonly
AS
BEGIN
--loop through metadata and insert records --
DECLARE #mkey nvarchar(max);
DECLARE #mvalue nvarchar(max);
DECLARE mCursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT mkey, mvalue
FROM #metadataList;
OPEN mCursor;
FETCH NEXT FROM mCursor INTO #mkey, #mvalue; -- Initial fetch attempt
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO template_field_metadata (name, value, template_field_id, isProperty) values (#mkey, #mvalue, 1, 0)
PRINT 'A new metadata created with id : ' + cast(SCOPE_IDENTITY() as nvarchar);
FETCH NEXT FROM mCursor INTO #mkey, #mvalue; -- Attempt to fetch next row from cursor
END;
CLOSE mCursor;
DEALLOCATE mCursor;
END
GO
Step 3: finally I executed the stored procedure like;
DECLARE #metadataToInsert TypeMetadata;
INSERT INTO #metadataToInsert VALUES ('value', 'callVariable2');
INSERT INTO #metadataToInsert VALUES ('maxlength', '30');
DECLARE #fid INT;
EXEC [dbo].[createfield] #name = 'prefagent', #text = 'Pref Agent', #order = 1 , #type= 'prefagent', #column_id = 0, #tid = 49, #metadataList =#metadataToInsert;

Resources